gpt4 book ai didi

C#生成一个在编译时返回类型未知的lambda表达式

转载 作者:行者123 更新时间:2023-11-30 17:46:03 24 4
gpt4 key购买 nike

假设我有以下方法:

public static String GetString(int a) {
return "";
}

public static int GetInt(int a) {
return 0;
}

现在我想为这些方法之一创建一个 lambda 表达式,我在编译时只知道以下内容:

方法信息方法信息;以上方法之一的方法信息。

属性类型属性类型;上述方法之一的返回类型的属性类型。

我不能在这里使用泛型类型,因为我不知道我希望在编译时调用哪个方法。

场景:

我有以下模型类:

public class Model {
public String Name {
get;set;
}

public int Number {
get;set;
}
}

在运行时我希望向这个模型注入(inject)信息。

public static void Inject<T>(T model) {
foreach(PropertyInfo propertyInfo in typeof(T).GetProperties()) {
Func<int, object> funcGet = GetValueFunc(propertyInfo.PropertyType);
propertyInfo.SetValue(model, funcGet.Invoke(0));
}
}

public static Func<int, object> GetValueFunc(Type propertyType) {
MethodInfo methodInfo = // say I know the method info here mapped to the propertyType

// this won't work since object isn't of either int or String
var iParam = Expression.Parameter(typeof(int), "iParam");
var call = Expression.Call(methodInfo, iParam);
var lambda = Expression.Lambda<Func<int, object>>(call, iParam);
return lambda.Compile();
}

有没有办法真正做到这一点?

我知道你可以做 Expression.Convert(Expression.Parameter(typeof(object), "o"), propertyType);如果您不知道运行时参数的类型。对于返回类型是否有类似的方法?

最佳答案

好吧,您并没有完全转换“返回类型”,因为您没有修改现有的方法代码。您需要转换该方法调用的结果,这是完全可行的,几乎使用您所说的内容:

var call = Expression.Call(methodInfo, iParam);
var cast = Expression.Convert(call, typeof (Object));
var lambda = Expression.Lambda<Func<int, Object>>(cast, iParam);

关于C#生成一个在编译时返回类型未知的lambda表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26803056/

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