如何在表达式树中使用隐式强制转换
本文关键字:转换 表达式 | 更新日期: 2023-09-27 18:13:02
我已经简化了程序,它使用表达式:
public class Program
{
public static IEnumerable<char> foo1()
{
// For some reason I cannot change result type
return new char[] { 's', '1' };
}
public static string foo2()
{
// For some reason I cannot change result type
return "s1";
}
static void Main()
{
Expression cond = Expression.Condition(Expression.Constant(true),
Expression.Call(typeof(Program).GetMethod("foo1")),
Expression.Call(typeof(Program).GetMethod("foo2")));
}
}
在执行过程中,我有以下错误
参数类型不匹配。
据我所知,c#不使用隐式类型转换。我该如何解决这个问题?
在构建表达式时,它不会为您添加隐式转换。您需要明确指出您希望使用Expression.Convert
应用转换操作符。
Expression cond = Expression.Condition(Expression.Constant(true),
Expression.Call(typeof(Program).GetMethod("foo1")),
Expression.Convert(Expression.Call(typeof(Program).GetMethod("foo2")), typeof(IEnumerable<char>)));