C# interface的使用

接口内部只包含方法、属性、事件或索引器的签名。继承接口的类必须实现接口中定义的接口成员。
接口可以用来实现多继承。

示例
class Program
{
    static void Main(string[] args)
    {
        Student stu = new Student();
        stu.Sex = "Male";
        OutPutStd(stu); //Sorry,Who am I? Male

        CollegeStu cstu = new CollegeStu();
        cstu.Sex = "Female";
        OutPutStd(cstu); //Sorry,Who am I? Female
        Console.ReadKey();

    }
    static void OutPutStd(Person p)
    {
        Console.WriteLine(p.Name());
        Console.WriteLine(p.Sex);
    }
}

public interface Person
{
    string Name();
    string Sex { get; set; }
}

public class Student : Person
{
    private string _sex;
    public string Sex
    {
        get { return _sex; }
        set { _sex = value; }
    }
    public string Name()
    {
        return "Sorry,Who am I?";
    }
} 
public class CollegeStu : Student
{}

猜你喜欢

转载自blog.csdn.net/yirol_/article/details/82051543