How can C # copy mem structures but cannot check for equality?

I can assign one structure value to another, and the memory is automatically copied. But if I want to check whether the two structures contain the same data (as if I just performed the task), I must explicitly encode it. Why is this? It looks like the structure should have a standard implementation of the == operator for structs.

+3
source share
3 answers

The structure has a standard implementation Equals. An operator ==is a C # function that you must implement yourself, using Equalsif you want.

+5
source

ValueType.Equals , . , :

s1 = ...;
s2 = ...;
s1.Equals(s2);

"" , .

, # , , , , .

, , # , , .

+6

If you have permission to use your own code, just call 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));
}
-2
source

All Articles