c# – 实现多个接口的参数

给以下代码:

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){}之类的东西.

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

转载注明原文:c# – 实现多个接口的参数 - 代码日志