What is the algorithm used by the memberwise equality test in .NET structs?

前端 未结 5 1436
再見小時候
再見小時候 2021-02-07 16:04

What is the algorithm used by the memberwise equality test in .NET structs? I would like to know this so that I can use it as the basis for my own algorithm.

I am trying

5条回答
  •  执笔经年
    2021-02-07 16:18

    public static bool CompareMembers(this T source, T other, params Expression>[] propertiesToSkip)
    {
        PropertyInfo[] sourceProperties = source.GetType().GetProperties();
    
        List propertiesToSkipList = (from x in propertiesToSkip
                                             let a = x.Body as MemberExpression
                                             let b = x.Body as UnaryExpression
                                             select a == null ? ((MemberExpression)b.Operand).Member.Name : a.Member.Name).ToList();
    
        List lstProperties = (
            from propertyToSkip in propertiesToSkipList
            from property in sourceProperties
            where property.Name != propertyToSkip
            select property).ToList();
    
        return (!(lstProperties.Any(property => !property.GetValue(source, null).Equals(property.GetValue(other, null)))));
    }
    

    How to use:

    bool test = myObj1.MemberwiseEqual(myObj2,
            () => myObj.Id,
            () => myObj.Name);
    

提交回复
热议问题