Generic method where T is type1 or type2

后端 未结 7 2111
陌清茗
陌清茗 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:20

    I know this is an old question, and this doesn't perfectly answer it, but you can do this with a single method, rather than creating multiples, or using generic constraints... especially useful if you have 20 odd types to check.

    Obviously you don't get the compiler type checking as you do when using a constraint, but this can help in certain circumstances...

    public void MyMethod()
    {
        if (!typeof(T).Equals(typeof(int)) &&
            !typeof(T).Equals(typeof(long)))
                throw new Exception("T must be int or long");
    
        //your logic here
    }
    

提交回复
热议问题