实现多个接口的参数

3
给定以下代码:
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个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接