简体   繁体   English

c# 表达式树:使用输出参数调用方法?

[英]c# Expression tree: call method with out-parameter?

For example: I want to call the例如:我想调用

Int32.TryParse(String numberStr, out Int32 result)

in Expression tree , but I do not know how to get the result of parsing.Expression tree ,但我不知道如何得到解析的结果。

You don't need to do anything special to call methods which take out parameters when using Expressions: just treat it as any other parameter, and the runtime takes care of it.在使用表达式时,您不需要做任何特殊的事情来调用out参数的方法:只需将其视为任何其他参数,运行时会处理它。

Here's an example of doing something like:这是执行以下操作的示例:

void Lambda(string input)
{
    int parsed;
    int.TryParse(input, out parsed);
    Console.WriteLine("Parsed: {0}", (object)parsed);
}

using expressions:使用表达式:

public static void Main()
{
    var inputParam = Expression.Parameter(typeof(string), "input");
    var parsedVar = Expression.Variable(typeof(int), "parsed");

    var tryParseCall = Expression.Call(
        typeof(int),
        "TryParse",
        null,
        inputParam,
        parsedVar); // <-- Here we pass 'parsedVar' as the 'out' parameter

    var writeLineCall = Expression.Call(
        typeof(Console),
        "WriteLine",
        null,
        Expression.Constant("Parsed: {0}"),
        Expression.Convert(parsedVar, typeof(object)));

    var lambda = Expression.Lambda<Action<string>>(
        Expression.Block(
            new[] { parsedVar },
            tryParseCall,
            writeLineCall),
        inputParam);

    var compiled = lambda.Compile();
    compiled("3");
}

See it working on dotnetfiddle看到它在 dotnetfiddle 上工作

The result is stored in the variable result (as you named in your out parameter).结果存储在变量result中(正如您在 out 参数中命名的那样)。 Try parse attempts to parse your input, and if it succeeds, it returns true and puts the resulting value in the named out parameter. Try parse 尝试解析您的输入,如果成功,则返回true并将结果值放入命名的 out 参数中。 Otherwise, it returns false and the out parameter is rendered invalid.否则,它返回false并且 out 参数被渲染为无效。 You would use it like so.你会像这样使用它。

if (Int32.TryParse(String numberStr, out Int32 result)) {
    // do something with `result`
}

// something went wrong (failure state - maybe with an `else`?)

Can you please try it with underscore "_"你能用下划线“_”试试吗

List<string> lstNumbs = new List<string>() {"f", "d", "7", "4", "5", "4", "2"};

var result = lstNumbs.Where(c => Int32.TryParse(c, out int _)).Select(s => s);

foreach (var item in result)
{
    Console.WriteLine(item);
}

Demo: https://dotnetfiddle.net/GdbgIZ演示: https://dotnetfiddle.net/GdbgIZ

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

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