Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

c# - Why can't I use System.ValueType as a generics constraint?

  • 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); }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two differences between using

where T : struct

and

where T : ValueType
  • the latter would allow T to be ValueType 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...