Generic method where T is type1 or type2

后端 未结 7 1857
陌清茗
陌清茗 2021-02-12 01:58

Is there a way to declare a generic function that the generic type is of type1 or type2?

example:

public void Foo(T number)
{
}         


        
7条回答
  •  太阳男子
    2021-02-12 02:21

    I also had this problem and I think I found a better solution (assuming an overloaded version of your method is insufficient):

    Mixing Type1 and Type2 without any parallels does not make any sense as has been written already. So there has to be any method or property accessed for both object types. To make sure for the compiler that these methods or properties are available for your object, group Type1 and Type2 by creating an interface MyInterface and implementing it by Type1 and Type2:

    interface MyInterface {
      void MyCommonMethod();
      bool MyCommonProperty { get; }
    }
    
    class Type1 : MyInterface {
      void MyCommonMethod() {
        // TODO: Implement it for Type1
      }
    
      bool MyCommonProperty {
      get {
        // TODO: Implement it for Type1
      }
      }
    }
    
    class Type2 : MyInterface {
      void MyCommonMethod() {
        // TODO: Implement it for Type2
      }
    
      bool MyCommonProperty {
      get {
        // TODO: Implement it for Type2
      }
      }
    }
    

    Now, to rewrite your Foo method to accept both Type1 and Type2, constraint T to be an MyInterface object:

    public void Foo(T number) where T : MyInterface
    {
      throw new NotImplementedException();
    }
    

    I mope this might be helpful. :)

提交回复
热议问题