Interface with generic parameter vs Interface with generic methods

前端 未结 4 1161
别那么骄傲
别那么骄傲 2020-12-08 02:34

Let\'s say I have such interface and concrete implementation

public interface IMyInterface
{
    T My();
}

public class MyConcrete : IMyInterface&l         


        
4条回答
  •  情话喂你
    2020-12-08 03:02

    Your generic method implementation has to be generic as well, so it has to be:

    public class MyConcrete2 : IMyInterface2
    {
        public T My()
        {
            throw new NotImplementedException();
        }
    }
    

    Why you can't do My() here? Because interface contract needs a method, that could be called with any type parameter T and you have to fulfill that contract.

    Why you can't stop genericness in this point? Because it would cause situations like following:

    Class declarations:

    public interface IMyInterface2
    {
        T My(T value);
    }
    
    public class MyClass21 : IMyInterface2
    {
        public string My(string value) { return value; }
    }
    
    public class MyClass22 : IMyInterface2
    {
        public int My(int value) { return value; }
    }
    

    Usage:

    var item1 = new MyClass21();
    var item2 = new MyClass22();
    
    // they both implement IMyInterface2, so we can put them into list
    var list = new List();
    list.Add(item1);
    list.Add(item2);
    
    // iterate the list and call My method
    foreach(IMyInterface2 item in list)
    {
        // item is IMyInterface2, so we have My() method. Choose T to be int and call with value 2:
        item.My(2);
    
        // how would it work with item1, which has My implemented?
    }
    

提交回复
热议问题