Casting an object to a generic interface

后端 未结 3 1920
感情败类
感情败类 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:14

    unfortunately inheritance doesn't work with generics. If your function expects IRelativeTo, you can make the function generic as well:

    void MyFunction<T>(IRelativeTo<T> sth) where T : IObject
    {}
    

    If I remember correctly, when you use the function above you don't even need to specify the type, the compiler should figure it out based on the argument you supply.

    If you want to keep a reference to one of these IRelativeTo objects inside a class or method (and you don't care what T is that), you need to make this class/method generic again.

    I agree, it is a bit of pain.

    0 讨论(0)
  • 2020-12-09 16:30

    If all you care about is that IRelativeTo deals with IObjects then you don't need to make it generic:

    interface IRelativeTo
     {
       IObject getRelativeTo();
       void setRelativeTo(IObject relativeTo)
     }
    

    The implementing classes may still be generic, however:

    abstract class RelativeTo<T>  : IRelativeTo where T : IObject
     {  
       public virtual T getRelativeTo() {return default(T);}
    
       public virtual void setRelativeTo(T relativeTo) {}
    
       IObject IRelativeTo.getRelativeTo() {return this.getRelativeTo(); }
    
       void IRelativeTo.setRelativeTo(IObject relativeTo) 
        { this.setRelativeTo((T) relativeTo);
        }
     }
    
    class AdminRateShift :  RelativeTo<AdminRateShift>, IObject {}
    

    Then you can do this:

      IRelativeTo irt = new AdminRateShift();
      IObject o = irt.getRelativeTo();
      irt.setRelativeTo(o);
    
    0 讨论(0)
  • 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<T> : 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<T>() where T : IObject
    {
        IRelativeTo<IObject> foo = // etc
    }
    

    If the IRelativeTo<T> 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<SomeType>(foo);
    

    There are benefits to both approaches.

    0 讨论(0)
提交回复
热议问题