具有相同签名成员已经定义了不同类型约束 [英] Member with the same signature already defined with different type constraints

查看:206
本文介绍了具有相同签名成员已经定义了不同类型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾与超载有这似乎排他性不同的约束方式运行跨越的问题。这是我的例子:

I have run across an issue with overloading methods that have different constraints that seems exclusive. That is my example:

public class A
{
    public void Do<T>() where T : class
    {

    }

    public void Do<T>() where T : struct 
    {

    }
}

这不能编译,出现以下错误会员与已经定义了相同的签名。是否有可能满足这两个条件的同时或它的C#编译器只是限制?

And this does not compile with the following error "Member with the same signature already defined". Is it possible to satisfy both conditions at once or it's just the limitation of the C# compiler?

推荐答案

这不是一种限制的编译器的 - 它的的语言的(并且很可能是一个限制CLR为好;我不知道)

It's not a limitation of the compiler - it's a limitation of the language (and quite possibly the CLR as well; I'm not sure).

从根本上那些冲突重载 - 这就像试图返回类型超载。它不支持。

Fundamentally those are clashing overloads - it's like trying to overload by return type. It's not supported.

它的的可以声明方法,使得这些调用所有编译成不同的方法调用:

It is possible to declare methods such that these calls all compile to invocations of different methods:

a.Do<int>();
a.Do<string>();
a.Do<int?>();

...但它总是涉及可选的参数和/或参数数组,它的<一个href="http://msmvps.com/blogs/jon_skeet/archive/2010/11/02/evil-$c$c-overload-resolution-workaround.aspx">horrible.

另外请注意,虽然你不能用一般的约束超载,你的可以的过载由通用的元数(类型参数的数量):

Also note that although you can't overload by generic constraints, you can overload by the generic "arity" (the number of type parameters):

public void Foo() {}
public void Foo<T>() {}
public void Foo<T1, T2>() {}

这篇关于具有相同签名成员已经定义了不同类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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