我正在尝试创建一个通用操作代表
delegate void ActionPredicate<in T1, in T2>(T1 t1, T2 t2);
和
public static ActionPredicate<T,string> GetSetterAction<T>(string fieldName)
{
ParameterExpression targetExpr = Expression.Parameter(typeof(T), "Target");
MemberExpression fieldExpr = Expression.Property(targetExpr, fieldName);
ParameterExpression valueExpr = Expression.Parameter(typeof(string), "value");
MethodCallExpression convertExpr = Expression.Call(typeof(Convert), "ChangeType", null, valueExpr, Expression.Constant(fieldExpr.Type));
UnaryExpression valueCast = Expression.Convert(convertExpr, fieldExpr.Type);
BinaryExpression assignExpr = Expression.Assign(fieldExpr, valueCast);
var result = Expression.Lambda<ActionPredicate<T, string>>(assignExpr, targetExpr, valueExpr);
return result.Compile();
}
这是我的来电者
ActionPredicate<busBase, string> act = DelegateGenerator.GetSetterAction<busPerson>("FirstName");
这是业务对象
public abstract class busBase
{
}
public class busPerson : busBase
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string GetFullName()
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
这是我在编译过程中得到的错误
Cannot implicitly convert type 'BusinessObjects.ActionPredicate<BusinessObjects.busPerson,string>' to 'BusinessObjects.ActionPredicate<BusinessObjects.busBase,string>'. An explicit conversion exists (are you missing a cast?)
我的 GetSetterAction 正在返回 ActionPerdicate ,因为这里 T 是 busPerson ,我试图将它存储在 ActionPredicate 中,记住逆变。但它失败了。我不知道如何进一步进行。请帮忙..!