gpt4 book ai didi

c# - 'MyClass' 类型的 ParameterExpression 不能用于 'System.Object' 类型的委托(delegate)参数

转载 作者:太空宇宙 更新时间:2023-11-03 10:24:51 26 4
gpt4 key购买 nike

我构建了一个类型为 Func<object,bool> 的表达式树.但是当我尝试编译它时出现异常:

ParameterExpression of type 'MyClass' cannot be used for delegate parameter of type 'System.Object'

调用对象的类型在运行时之前是未知的。

Expression leftFunc, rightFunc;
var x = Expression.Parameter(t);
if (left_element.All(char.IsDigit))
leftFunc = Expression.Constant(int.Parse(left_element));
else
leftFunc = Expression.PropertyOrField(x, left_element);
if (right_element.All(char.IsDigit))
rightFunc = Expression.Constant(int.Parse(right_element));
else
rightFunc = Expression.PropertyOrField(x, right_element);
var result = Expression.Lambda<Func<object, bool>>(
Expression.GreaterThan(leftFunc, rightFunc), x); //exception thrown on this line
return result;

x类型为 MyClass ,我可以以某种方式使用转换器吗?

最佳答案

看完评论更新。

完整代码,有效:

void Main()
{
var method = something(typeof(MyClass), "propA", "propB");
var classes = new List<MyClass>();
classes.Add(new MyClass { propA = 1, propB = 2 }); // Should return false
classes.Add(new MyClass { propA = 3, propB = 2 }); // Should return true
classes.Add(new MyClass { propA = 2, propB = 2 }); // Should return false
var res = classes.Where(method);
res.Dump(); //Only class with propA = 3 && propB == 2 is returned
}

private Func<object, bool> something(Type t, string left_element, string right_element)
{
var props = t.GetProperties();
return (onObject) => {
int left_int;
object leftSide;
if (!int.TryParse(left_element, out left_int))
{
leftSide = props.FirstOrDefault (p => p.Name == left_element).GetValue(onObject);
} else {
leftSide = left_int;
}

int right_int;
object rightSide;
if (!int.TryParse(right_element, out right_int))
{
rightSide = props.FirstOrDefault (p => p.Name == right_element).GetValue(onObject);
} else {
rightSide = left_int;
}

return Comparer.Default.Compare(leftSide, rightSide) > 0;
};
}

private class MyClass {
public int propA {get;set;}
public int propB {get;set;}
}

关于c# - 'MyClass' 类型的 ParameterExpression 不能用于 'System.Object' 类型的委托(delegate)参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31977388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com