简体   繁体   中英

Parameters implementing multiple interfaces

Givin the following code:

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();
    }
}

Is there a way of implementing ShowLegs so that it only accepts values that implement IHasLegs and IHasName, without having to declare a intermediate IHasLegsAndHasName: IHasLegs, IHasName ? Something like ShowLegs((IHasLegs, IHasName) i) {}.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM