Casting an object to a generic interface

后端 未结 3 1919
感情败类
感情败类 2020-12-09 15:43

I have the following interface:

internal interface IRelativeTo where T : IObject
{
    T getRelativeTo();
    void setRelativeTo(T relativeTo);
}
         


        
3条回答
  •  有刺的猬
    2020-12-09 16:34

    If I understand the question, then the most common approach would be to declare a non-generic base-interface, i.e.

    internal interface IRelativeTo
    {
        object getRelativeTo(); // or maybe something else non-generic
        void setRelativeTo(object relativeTo);
    }
    internal interface IRelativeTo : IRelativeTo
        where T : IObject
    {
        new T getRelativeTo();
        new void setRelativeTo(T relativeTo);
    }
    

    Another option is for you to code largely in generics... i.e. you have methods like

    void DoSomething() where T : IObject
    {
        IRelativeTo foo = // etc
    }
    

    If the IRelativeTo is an argument to DoSomething(), then usually you don't need to specify the generic type argument yourself - the compiler will infer it - i.e.

    DoSomething(foo);
    

    rather than

    DoSomething(foo);
    

    There are benefits to both approaches.

提交回复
热议问题