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

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

    What you describe is called "template specialization" and doesn't work in C#. It is available in C++ but still hasn't made its way to C#.

    This has already been answered in "C# generic interface specialization". The short version is that you can't do it. You can work around it forcing runtime resolution but in this case using generics makes no sense. Generics should be used to use the same code on different types.

    Perhaps there is another way of doing what you really want. I've run in similar situations when implementing the Strategy or Template Method patterns, where I want most of the code to work in the general case but modify some specific steps.

    In such cases it's better to inject the custom steps to your class as interfaces, or even Func<> objects that specialize the behavior, when you actually create the "Template Method".

    Of course, there are a lot of other ways to do this, some of which work better than others for specific problems

提交回复
热议问题