Generic method where T is type1 or type2

后端 未结 7 1850
陌清茗
陌清茗 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

    Use overloaded methods instead:

    public void Foo(int number)
    {
    } 
    
    public void Foo(long number)
    {
    }
    

    You cannot perform arithmetical operations on generic types anyway. Note that you can pass an int value to a long parameter. It will automatically be converted to long. Having just a single method with a long parameter could therefore be sufficient.

    Older programming languages worked after the principle "There can be only one". C# allows you to have several methods with the same name in the same class, interface or struct. These methods must have a different signature. This means, that they must have a different number of parameters or parameters with different types (or both). This is called method overloading.

提交回复
热议问题