基于泛型约束的方法重载? [英] Method overloading based on generic constraints?

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

问题描述

我可以以某种方式重载只有通用类型约束的方法吗?

这不会编译:

  void Foo< T>( T bar)其中T:class 
{

}

void Foo< T>(T bar)其中T:struct
{






$ b

由于这些都是开放方法,所以实际的方法应该是关闭/在代码中的其他地方用具体类型的 T 引用时被构造/完全定义,然后清楚要调用哪个超载。



显而易见的解决方案不是重载它们,但我想知道为什么这在C#中不起作用?



其他问题:如果这只是一个C#编译器约束,IL是否允许这样的重载?

$ b

我可以以某种方式重载只有泛型类型约束的方法吗?


没有。它不是重载方法签名的一部分,就像返回类型不是。



horrible 在某些情况下伪超载我不建议沿着这条路走下去。



有关更多信息,您可能需要阅读:




Can I somehow have overloaded methods which differ only by generic type constraints?

This does not compile:

    void Foo<T>(T bar) where T : class
    {

    }

    void Foo<T>(T bar) where T : struct
    {

    }

Since these are "open" methods, the actual method should be closed/constructed/fully-defined when it's referenced elsewhere in code with a concretely-typed T, and then it would be clear which overload to call.

The obvious solution is not to overload them, but I'm wondering why this doesn't work in C#?

Additional question: If this is just a C# compiler constraint, does the IL allow such an overload?

解决方案

Can I somehow have overloaded methods which differ only by generic type constraints?

No. It's not part of the method signature in terms of overloading, just like the return type isn't.

There are horrible ways of "pseudo-overloading" in some cases, but I wouldn't recommend going down that path.

For more information, you might want to read:

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

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