How to call a method overload based on closed generic type?

后端 未结 6 2021
时光取名叫无心
时光取名叫无心 2021-02-13 10:20

Suppose I have three methods:

void Foo(MemoryStream v) {Console.WriteLine (\"MemoryStream\");}
void Foo(Stream v)       {Console.WriteLine (\"Stream\");}
void Fo         


        
6条回答
  •  暖寄归人
    2021-02-13 10:53

    This can only be done using dynamic binding, e.g. like this:

    void Bar(T value)
    {
        dynamic parameter = value;
        Foo(parameter); 
    }
    

    Note that dynamic dispatch uses the actual runtime type of the actual runtime object to do method dispatch, so there has to be an object. If value is null, this will not work.

提交回复
热议问题