Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何创建一个方法,该方法接受两个相同类型的对象、一个属性并比较值_C#_Compare - Fatal编程技术网

C# 如何创建一个方法,该方法接受两个相同类型的对象、一个属性并比较值

C# 如何创建一个方法,该方法接受两个相同类型的对象、一个属性并比较值,c#,compare,C#,Compare,我正在尝试创建一个helper函数(针对一个类),它接受两个对象并比较两个类上的属性 这些属性只是像string、int和bool 用法 Compare(widget1,widget2,x => x.Name) 到目前为止我拥有的 private void CompareValue<T>(Order target, Order source, Func<Order, T> selector) { if(target.selector != sou

我正在尝试创建一个helper函数(针对一个类),它接受两个对象并比较两个类上的属性

这些属性只是像
string
int
bool

用法

Compare(widget1,widget2,x => x.Name)
到目前为止我拥有的

  private void CompareValue<T>(Order target, Order source, Func<Order, T> selector)
  {
     if(target.selector != source.selector)
     {
       // do some stuff here
     }
  }
private void CompareValue(订单目标、订单源、函数选择器)
{
if(target.selector!=source.selector)
{
//在这里做些事情
}
}

显然,上面的代码不起作用

您可以添加一个约束:

private void CompareValue(订单目标、订单源、函数选择器)
其中T:i可满足
{
如果(!选择器(目标).Equals(选择器(源))
{
//做你的事
}
}
这将处理您指定的类型(以及许多其他类型),并允许编译器保护您不受可能不合适的用例的影响


请注意,您还需要调用
Func
,即:
选择器(目标)
选择器(源)
,以创建结果值。

如果您想要一个完全通用的版本:

public void CompareValue<TModel,TProperty>(TModel x, TModel y, Expression<Func<TModel, TProperty>> expression)
    where TModel : class
    where TProperty : IEquatable<TProperty>
{
    MemberExpression memberExpression = expression.Body as MemberExpression;
    Type modelType = typeof(TModel);
    PropertyInfo propInfo = modelType.GetProperty(memberExpression.Member.Name);

    TProperty xValue = (TProperty)propInfo.GetValue(x);
    TProperty yValue = (TProperty)propInfo.GetValue(y);
    if (xValue.Equals(yValue))
    {
        Console.WriteLine("Match!");
    }
}

我希望有一个很酷的
nameof
技巧,可以消除lambda表达式。没有这样的运气。似乎对字符串不起作用,memberExpression为null。我是否使用它不正确?(示例)正确,当TModel是一个对象并且表达式是针对一个属性时,这似乎是可行的,但是我的技能不太合适why@Default:如果你只是比较直接的对象,那就违背了表达式的目的,不是吗?如果你想比较
x
vs
y
直接,你可能只需要一个
CompareValue(tx,ty),其中T:IEquatable
方法签名。表达式用于引用属性。
public void CompareValue<TModel,TProperty>(TModel x, TModel y, Expression<Func<TModel, TProperty>> expression)
    where TModel : class
    where TProperty : IEquatable<TProperty>
{
    MemberExpression memberExpression = expression.Body as MemberExpression;
    Type modelType = typeof(TModel);
    PropertyInfo propInfo = modelType.GetProperty(memberExpression.Member.Name);

    TProperty xValue = (TProperty)propInfo.GetValue(x);
    TProperty yValue = (TProperty)propInfo.GetValue(y);
    if (xValue.Equals(yValue))
    {
        Console.WriteLine("Match!");
    }
}
CompareValue(widget1, widget2, x => x.Name);