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

后端 未结 6 2100
时光取名叫无心
时光取名叫无心 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:49

    I had the same issue, and the unique solution I knew was try-casting it until I got something other than null. Then, I would have the correct type at compile time and the compiler would know the right overload to call. I could not find another way to achieve this 'run-time polymorphism'.

    To avoid using a dictionary or a switch-like solution (poor maintainability,as pointded out by Marc), just call Method((dynamic) o) and DLR will call the correct overload method according to the run-time type.

    Just remember to:

    1) Provide a default overload with the most top type possible;

    2) Watch out for any ambiguity during resolution of type at run-time (i.e. two indepenent interfaces and one implementation that uses both);

    3) Handle null case.

    You can read more about it here.

    Hope I've helped.

提交回复
热议问题