English 中文(简体)
通用体内无约束类型参数规则(C#)
原标题:Rules of Unbounded type parameters in Generics ( C# )

我是新来的。

我开始从微软网站学习通用物

我无法理解下面关于无约束的类型参数。

Type parameters that have no constraints, such as T in public class SampleClass{}, are called unbounded type parameters.

Unbounded type parameters have the following rules: You can compare to null. If an unbounded parameter is compared to null, the comparison will always return false if the type argument is a value type.

我没有发现上述任何例子。 如果有人给我以榜样来理解这些要点,那将是巨大的。

问题回答

这两项职能都产生了相同的国际空间法研究所;

bool Test1<T>(T val) => val == null;
bool Test2<T>(T val) where T:class => val == null;

IL_0000: ldarg.0
IL_0001: box !!T
IL_0006: ldnull
IL_0007: ceq
IL_0009: ret

1. 如果电离层穿透面值;

Test1<int>(0) == false;

然后,在标的中将打上ger子,这总是会导致非核参考。 因此,与<代码>null的比较总是虚假的。

通过<代码>Nullable<T>的论点也属于罚款,结果与IL。

bool Test3<T>(T? val) where T:struct => val == null;
bool Test4<T>(T? val) where T:struct => !val.HasValue;

IL_0000: ldarga.s val
IL_0002: call instance bool valuetype [System.Runtime]System.Nullable`1<!!T>::get_HasValue()
IL_0007: ldc.i4.0
IL_0008: ceq
IL_000a: ret

但是,没有违约的<代码>= 价值类型操作者;

bool Test5<T>(T val) where T:struct => val == null;
bool Test6<T>(T val) where T:struct => val == default(T);

error CS0019: Operator  ==  cannot be applied to operands of type  T  and  <null> 
error CS0019: Operator  ==  cannot be applied to operands of type  T  and  T 

相反,你可以使用缺省比较器;

public bool Test7<T>(T val) => EqualityComparer<T>.Default.Equals(val, default(T));

自2008年起 7 您可以添加一个制约因素,由数字类型加以实施;

public bool Test8<T>(T val) where T : IEqualityOperators<T,T,bool> => val == default(T);




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签