Generic method where T is type1 or type2

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

    For ReferenceType objects you can do

    public void DoIt(T someParameter) where T : IMyType
    {
    
    }
    

    ...

    public interface IMyType
    {
    }
    
    public class Type1 : IMyType
    {
    }
    
    public class Type2 : IMyType
    {
    }
    

    For your case using long as parameter will constrain usage to longs and ints anyway.

    public void DoIt(long someParameter)
    {
    
    }
    

    to constrain to any value types (like: int, double, short, decimal) you can use:

    public void DoIt(T someParameter) where T : struct
    {
    
    }
    

    for more information you can check official documentation here

提交回复
热议问题