首页 > 解决方案 > C# - 获取以元组作为输出的方法,但多次执行相同的参数?

问题描述

我是编码和 C# 的新手,我想知道如果您使用元组作为返回值,一个方法是否会被多次调用?

可能缺少此描述,因为我不是英语母语,所以这里有一些示例代码:

public static (bool Correct, string Output) MyMethod1(int MyArgument)
{
    // Do something
    return (true, MyOutput);
}

public void Execute()
{
    if (MyMethod1(100).Correct)
    {
        Console.WriteLine(MyMethod1(100).Output);
    }
}

所以我想知道我们现在是否通过整个方法 MyMethod1 两次或一次,因为参数是相同的。

非常感谢。

如果我做错了什么,也请让我知道,发布这个。因为我也是新手。

标签: c#methodstuplesreturn-value

解决方案


在这种情况下,要让你的方法只执行一次,你应该像这样存储方法的检索结果:

public static (bool Correct, string Output) MyMethod1(int MyArgument)
{
    // Do something
    return (true, MyOutput);
}

public void Execute()
{
    (bool correct, string output) result = MyMethod(100);
    if (result.correct)
    {
        Console.WriteLine(result.output);
    }
}

推荐阅读