English 中文(简体)
C# Value型直接比较
原标题:Direct comparisons of C# Value types

I have read the following statement regarding to the comparison of C# value types in C# in Depth, Second Edition several times.

第77页

当一类参数未经约束时(对其不适用任何限制),你可以使用=和!=操作者,但只能将这种数值与无效进行比较。 你不能相互比较两种T型数值。

......

当某一类参数被限制为价值类型时,=和! 根本不能使用。

If I understand (I don t think so) it correctly, it basically tells me that you cannot use == or != to compare two value types. Why why why?

It will be better if a simple example can be given for this case. Can someone give me a little idea what the above paragraph tries to convey?

最佳回答

这只是限制价值类型时的意思(第二段)。

static bool TryToCompare<T>(T first, T second) where T : struct
{
    return first == second; // not legal
    return first.Equals(second); // legal
}

如果不对一般产品实行价值类型的限制,它也说了这一点(第一段)。

static bool TryToCompare<T>(T first, T second) 
{
    return first == second; // not legal
    return first == null; // legal
    return first.Equals(second); // legal
}

如果你将<代码>T限制在参考类别中,你可以放弃使用=

static bool TryToCompare<T>(T first, T second) where T : class
{
    return first == second; // legal
    return first == null; // legal
    return first.Equals(second); // legal
}
问题回答

物体是可比的,因为使用 = 进行的比较是检测该参考资料是否相同(记忆地址)。 如果(指示1.Equals(string2)的话,你通常会使用。

我不理解的是,我看到的情况是:=以体力开展工作,而情况是:





相关问题
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. ...

热门标签