实现多个接口的参数

时间:2015-05-02 22:01:01

标签: c# parameters interface

发现以下代码:

internal interface IHasLegs
{
    int NumberOfLegs { get; }
}

internal interface IHasName
{
    string Name { get; set; }
}

class Person : IHasLegs, IHasName
{
    public int NumberOfLegs => 2;
    public string Name { get; set; }

    public Person(string name)
    {
        Name = name;
    }
}

class Program
{
    static void ShowLegs(IHasLegs i)
    {
        Console.WriteLine($"Something has {i.NumberOfLegs} legs");
    }
    static void Main(string[] args)
    {
        Person p = new Person("Edith Piaf");

        ShowLegs(p);

        Console.ReadKey();
    }
}

有没有办法实现ShowLegs,以便它只接受实现IHasLegs和IHasName的值,而不必声明中间的IHasLegsAndHasName:IHasLegs,IHasName?像ShowLegs((IHasLegs,IHasName)i){}。

1 个答案:

答案 0 :(得分:10)

static void ShowLegs<T>(T i) where T : IHasLegs, IHasName
{
    Console.WriteLine($"{i.Name} has {i.NumberOfLegs} legs");
}