如何基于封闭的泛型类型调用方法重载? [英] How to call a method overload based on closed generic type?

查看:75
本文介绍了如何基于封闭的泛型类型调用方法重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三种方法:

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

我调用方法Foo传递开放通用类型的第一个参数:

I call method Foo passing first parameter of open generic type:

void Bar<T>()
{
    Foo(default(T)); //just to show the scenario
    //default(T) or new T() doesn't make a difference, null is irrelevant here
}

我想调用MemoryStream重载,所以我用MemoryStream关闭方法Bar的通用类型:

I want to call MemoryStream overload, so I close generic type of method Bar with MemoryStream:

Bar<MemoryStream>();

,但调用object重载.如果将通用约束添加到Foo签名where T : Stream,则将调用Stream版本.

but the object overload is called. If I add generic constraint to Foo signature where T : Stream, then the Stream version is called.

基于开放的通用类型T,是否可以将方法调用分派给MemoryStream重载?

Is there a way to dispatch method call to MemoryStream overload, based on open generic type T?

我不想使用Delegate.CreateDelegate或其他反射API.只是使用C#语言.我可能在语言本身中缺少一些东西.

I don't want to use Delegate.CreateDelegate or other Reflection APIs. Just in the means of C# language. I'm probably missing something within the language itself.

在这种情况下,将值类型作为封闭的泛型类型并使用静态方法进行了尝试.

Tried this scenario with value types as closed generic type and using static methods.

推荐答案

您描述的内容称为模板特殊化",在C#中不起作用.它可以在C ++中使用,但仍未移植到C#中.

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#.

" 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.

在这种情况下,最好在实际创建模板方法"时将自定义步骤作为类甚至专门用于行为的Func<>对象注入类中.

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

这篇关于如何基于封闭的泛型类型调用方法重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆