问题描述
我想以下情况来区分:
- 一个普通的值类型(如
INT
) - 一个空值类型(例如
INT?
) - 引用类型(如
字符串
) - 可选,我不会介意这个映射到(1)或(2)上述
- A plain value type (e.g.
int
) - A nullable value type (e.g.
int?
) - A reference type (e.g.
string
) - optionally, I would not care if this mapped to (1) or (2) above
我想出了以下code,工作正常病例(1)和(2):
I have come up with the following code, which works fine for cases (1) and (2):
static void Foo<T>(T a) where T : struct { } // 1
static void Foo<T>(T? a) where T : struct { } // 2
不过,如果我尝试检测情况(3)这样,它不会编译:
However, if I try to detect case (3) like this, it does not compile:
static void Foo<T>(T a) where T : class { } // 3
该错误消息的键入'X'已经定义了一个名为'富'具有相同的参数类型成员的。好了,不知何故,我不能让之间的差异其中T:结构
和其中T:类
The error message is Type 'X' already defines a member called 'Foo' with the same parameter types. Well, somehow I cannot make a difference between where T : struct
and where T : class
.
如果我删除了第三个功能(3),下面的code不能编译之一:
If I remove the third function (3), the following code does not compile either:
int x = 1;
int? y = 2;
string z = "a";
Foo (x); // OK, calls (1)
Foo (y); // OK, calls (2)
Foo (z); // error: the type 'string' must be a non-nullable value type ...
我如何获得美孚(Z)
来编译,将其映射到上述功能中的一个(或第三个与其他约束,这是我没有想到的)?
How can I get Foo(z)
to compile, mapping it to one of the above functions (or a third one with another constraint, which I have not thought of)?
推荐答案
约束不是签名的组成部分,但参数。而在参数限制重载解析过程中执行。
Constraints are not part of the signature, but parameters are. And constraints in parameters are enforced during overload resolution.
现在,让我们把约束中的一个参数。它的丑陋,但它的作品。
So let's put the constraint in a parameter. It's ugly, but it works.
class RequireStruct<T> where T : struct { }
class RequireClass<T> where T : class { }
static void Foo<T>(T a, RequireStruct<T> ignore = null) where T : struct { } // 1
static void Foo<T>(T? a) where T : struct { } // 2
static void Foo<T>(T a, RequireClass<T> ignore = null) where T : class { } // 3
(优于从不迟到6年?)
(better six years late than never?)
这篇关于通用的约束,其中T:struct和其中T:类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!