为什么我不能用System.ValueType作为一个泛型约束? [英] Why can't I use System.ValueType as a generics constraint?
问题描述
- 为什么我不能用
的约束其中T:System.ValueType
? - 为什么Microsoft防止此类
被约束?
示例:
为什么我不能做以下
$ b $? b //定义在.NET类
公共无效巴≤; T>(T a)如T:值类型{...}
//在我的课
公共无效美孚中所定义; T>(T a)如T:值类型
{巴≤; T>(一); }
什么是使用结构上的ValueType?
$ B的区别$ b
//定义在我的课
公共无效美孚< T>(T A)其中T:结构
{巴≤; T>(一) ; }
有使用两个不同点
,其中T:结构
和
,其中T:值类型
- ,后者将允许
T
是值类型
本身,这是一个引用类型。 - 后者也将允许
T
是一个空值类型
第一,这些差异几乎从来没有你想要的。第二个可能的偶尔的是有用的; 可空< T>
是在于它满足有点奇怪,无论是其中T:结构
也不其中T:类
约束
更多有用的将是约束
其中T:结构,System.Enum
这是由C#禁止没有很好的理由,我可以告诉。请参见我的博客文章和的Unconstrained旋律项目了解这一点。
- Why can't I use a constraint of
where T : System.ValueType
? - Why does Microsoft prevent this type from being a constraint?
Example:
Why can't I do the following?
// Defined in a .Net class
public void bar<T>(T a) where T : ValueType {...}
// Defined in my class
public void foo<T>(T a) where T : ValueType
{ bar<T>(a); }
What is the difference in using struct over ValueType?
// Defined in my class
public void foo<T>(T a) where T : struct
{ bar<T>(a); }
There are two differences between using
where T : struct
and
where T : ValueType
- the latter would allow
T
to beValueType
itself, which is a reference type. - the latter would also allow
T
to be a nullable value type
The first of these differences is almost never what you want. The second could occasionally be useful; Nullable<T>
is slightly odd in that it satisfies neither the where T : struct
nor where T : class
constraint.
More useful would be the constraint
where T : struct, System.Enum
which is prohibited by C# for no good reason that I can tell. See my blog post and the Unconstrained Melody project for more on this.
这篇关于为什么我不能用System.ValueType作为一个泛型约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!