简体   繁体   English

如何在表达式树c#中使用隐式转换?

[英]How to use implicit casting in expression tree c#?

I have simplified program, which uses expressions: 我有简化的程序,它使用表达式:

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")));
    }
}

During execution I have following error 执行期间我有以下错误

Argument types do not match. 参数类型不匹配。

As I understood c# does not use implicit type casting. 据我所知,c#不使用隐式类型转换。 How can I solve this problem? 我怎么解决这个问题?

When building expressions it's not going to add in implicit conversions for you. 构建表达式时,它不会为您添加隐式转换。 You need to specifically indicate that you want to apply the conversion operator(s) using Expression.Convert . 您需要明确指出要使用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>)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM