[英]How is it that C# is able to copy the mem of a struct but not able to test for equality?
I can assign one struct's value to another and the memory gets copied automatically. 我可以将一个结构的值分配给另一个结构,并自动复制内存。 But if I want to test whether two structs contain the same data (as if I had just done an assignment), I have to explicitly code it.
但是,如果我想测试两个结构是否包含相同的数据(就好像我刚刚完成了一个赋值),我必须对其进行显式编码。 Why is that?
这是为什么? It seems like the framework should have a default implementation of operator == for structs.
看起来框架应该有一个默认的operator == for structs实现。
The default implementation of ValueType.Equals
does exactly what you want. ValueType.Equals
的默认实现完全符合您的要求。 So if you do: 所以,如果你这样做:
s1 = ...;
s2 = ...;
s1.Equals(s2);
The call to "Equals" will do the automatic deep comparison you are looking for. 对“Equals”的调用将进行您正在寻找的自动深度比较。
In general, C# tends to favor not using overloaded operators, which is probably why it doesn't implement the operator. 通常,C#倾向于不使用重载运算符,这可能是它不实现运算符的原因。
Also, philosophically, C# tends to shy away from implicit behavior, including things like implicit generation of methods. 而且,从哲学上讲,C#倾向于回避隐式行为,包括隐式生成方法等。
The framework has a default Equals
implementation. 该框架具有默认的
Equals
实现。 The ==
operator is a C# feature that you must implement yourself, using Equals
if you wish. ==
运算符是一个C#功能,您必须自己实现,如果您愿意,可以使用Equals
。
If you have the execute native code permission, just call memcmp
: 如果您具有执行本机代码权限,则只需调用
memcmp
:
static class memcmpsig<T> where T : struct
{
[DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)]
static extern int memcmp(ref T left, ref T right, UIntPtr count);
}
static class CompareExtension
{
int CompareTo<T>(this T left, T right) { return memcmpsig<T>::memcmp(left, right, Marshal::SizeOf(typeof(T));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.