C# 为什么所有 TryParse 重载都有一个 out 参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19592084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:23:00  来源:igfitidea点击:

Why do all TryParse overloads have an out parameter?

c#tryparse

提问by Misha Zaslavsky

I have discovered that many times I don't need the out parameter of the TryParse method, but the problem that it is necessarily. Here I will show one example when it's not needed.

我发现很多时候我不需要 TryParse 方法的 out 参数,但它是必然的问题。在这里,我将展示一个不需要时的示例。

I want to check if a string is an integer, if it is an integer then print "An integer"; otherwise, print "Not an integer". So here is the code:

我想检查一个字符串是否是一个整数,如果它是一个整数,则打印“一个整数”;否则,打印“不是整数”。所以这里是代码:

string value = Console.ReadLine(); //Get a value from the user.
int num; //Why should I have it?? No need at all !

if (int.TryParse(value, out num))
{
    Console.WriteLine("An integer");
}
else
{
    Console.WriteLine("Not an integer");
}

I am just wondering why TryParse always returns an out parameter? Why it doesn't have the overload without an out parameter?

我只是想知道为什么 TryParse 总是返回一个 out 参数?为什么没有 out 参数就没有重载?

回答by Tim Schmelter

TryParseis a relatively complex operation to determine the intrepresentation of a string. If there would be an overload that just returns a bool, it would be very likely that many (unexperienced) developers would follow this inefficient pattern:

TryParse是一个相对复杂的操作来确定 a 的int表示string。如果有一个只返回 a 的重载,bool很可能许多(没有经验的)开发人员会遵循这种低效模式:

int myInt = -1;
if(int.TryParse("123"))
    myInt = int.Parse("123");

回答by AllenG

It has the outparameter because the vast majority of the time when people use it, they want the int (or double, or decimal, or datetime, or whatever) that was parsed.

它具有out参数是因为人们在绝大多数时间使用它时,他们想要解析的 int(或双精度、十进制、日期时间或其他)。

If you don't want/need the parsed value, and you find yourself doing it all the time, you could write your own "wrapper" on .TryParse()that just takes the string.

如果您不需要/不需要解析的值,并且您发现自己一直在这样做,您可以编写自己的“包装器” .TryParse(),只需要字符串。

In this example (and you could make it more generic, I'm sure) you could do something like

在这个例子中(你可以让它更通用,我敢肯定)你可以做类似的事情

public static bool TryParseNoOutput(this string value)
{
  int noNeed = 0;
  return int.TryParse(value, out noNeed);
}

Then in your code (in this case) you'd call:

然后在你的代码中(在这种情况下)你会调用:

string value = Console.ReadLine();
if(value.TryParseNoOutput()) Console.WriteLine("An Integer");
else Console.WriteLine("Not an integer."):

Edit:As has been pointed out in the comments, I tried to call "int.TryParseNoOutput" when I had defined it as an extension on a string. Answer has been updated to reflect that.

编辑:正如评论中指出的那样,当我将“int.TryParseNoOutput”定义为字符串的扩展时,我尝试调用它。答案已更新以反映这一点。

回答by David

Updated Answer:

更新答案:

In more recent versions of C# you can declare the output parameter inline, which allows you to remove the line of code you don't want in your example:

在更新的 C# 版本中,您可以内联声明输出参数,这允许您删除示例中不需要的代码行:

string value = Console.ReadLine(); //Get a value from the user.

if (int.TryParse(value, out int num))
{
    Console.WriteLine("An integer");
}
else
{
    Console.WriteLine("Not an integer");
}

You can simply ignore the result in your code and no longer have that extra line. You still have the extra parameter, but so?

您可以简单地忽略代码中的结果,不再有多余的行。你仍然有额外的参数,但是呢?

The underlying "why" is still the same and is unlikely to ever change. The method needed to return two things, a boolindicating success and an intindicating the resulting value if successful. (I can't think of another way to convey the result, can you?) Since a method can only return one thing, and a custom result type seems like overkill for this, the decision was made to return the booland have the result be an outparameter. And once that decision was made, it has to remain for the duration of the language.

根本的“为什么”仍然相同,并且不太可能改变。该方法需要返回两件事,一个bool指示成功,一个指示成功时int的结果值。(我想不出另一种表达结果的方式,你能吗?)由于一个方法只能返回一个东西,而自定义结果类型对此似乎bool有点矫枉过正,决定返回并让结果为一个out参数。一旦做出这个决定,它就必须在语言的持续时间内保持不变。

"They" certainly couldadd an overload that doesn't output in the intvalue. But why? Why expend the effort in designing, documenting, testing, and as we've seen perpetuallysupporting a method that serves no purpose but to save a few keystrokes for an extreme minority of developers? Again, very unlikely.

“他们”当然可以添加一个不会在int值中输出的重载。但为什么?为什么要花费精力在设计、记录、测试上,并且正如我们所看到的那样,永远支持一种除了为极少数开发人员节省几次按键操作之外没有任何用处的方法?再次,非常不可能。

For such features you are certainly welcome to propose a change. It would be pretty cool to have a proposal accepted, I imagine. I doubt this one would be, but if you're passionate about it then by all means have at it.

对于此类功能,当然欢迎您提出更改建议。我想,如果提案被接受,那会很酷。我怀疑这个会是,但如果你对它充满热情,那么一定要尝试一下。



Original Answer:

原答案:

The short answer is, "Because that's how the method is defined." Perhaps by chance someone from the C# language team might find this question and provide reasoning into whydecisions were made, but that doesn't really change much at this point. C# is a statically compiled language and the method signatures need to match, so that's just the way it is.

简短的回答是,“因为这就是方法的定义方式。” 也许 C# 语言团队的某个人可能会偶然发现这个问题并提供有关做出决定的原因的推理,但这在这一点上并没有真正改变。C# 是一种静态编译语言,方法签名需要匹配,所以它就是这样。

(Imagine if they changed this and broke .TryParse()on all existing codebases. That would be... bad.)

(想象一下,如果他们改变了这一点并破坏.TryParse()了所有现有的代码库。那将是......糟糕。)

You might be able to work around this in your own code, though. Something as simple as an extension method could do the trick for you:

不过,您也许可以在自己的代码中解决这个问题。像扩展方法这样简单的东西可以为您解决问题:

public static bool IsInt(this string s)
{
    int x = 0;
    return int.TryParse(s, out x);
}

Then in your code you'd just need to call that method from the string value:

然后在您的代码中,您只需要从字符串值调用该方法:

string value = Console.ReadLine();
if (value.IsInt())
    Console.WriteLine("An integer");
else
    Console.WriteLine("Not an integer");

回答by Task

Why does TryParse have an out parameter?
For the very simple reason of how TryParse is implemented.
The way you determine whether or not something is parsable, is by parsing it! If you are able to parse something, then it is parsable. If you cannot parse it, then it is not parsable.

为什么 TryParse 有一个 out 参数?
对于如何实现 TryParse 的非常简单的原因。
确定某物是否可解析的方法是解析它!如果您能够解析某些内容,那么它就是可解析的。如果你不能解析它,那么它就不可解析。

Therefore, by way of determining if something is parsable or not, if it isparsable, then we have already parsed it! It would be silly to throw away this parsed value (anyone who's wondering whether or not something is parsable is likely interested in the parsed result), so the parsed value is returned.

所以,通过判断一个东西是否可解析,如果可解析的,那我们就已经解析了!丢弃这个解析值是愚蠢的(任何想知道某些东西是否可解析的人都可能对解析结果感兴趣),因此返回解析值。

It has an out parameter because the parsed value is a by-product of a true-returning TryParse call.

它有一个 out 参数,因为解析的值是返回 true 的 TryParse 调用的副产品。