Null out parameters in C#?

懵懂的女人 提交于 2020-01-11 08:09:47

问题


After reading on stackoverflow that in the case of checking the format of a DateTime you should use DateTime.TryParse. After trying some regex expressions they seem to get long and nasty looking to cover lots of the formatting.

But TryParse requires an "out" parameter and since I just want to do a validation format check I don't need the actual result.

So I am left with a variable that holds the "out" result and am to do nothing with it. Is there a way so I don't have to do a out parameter?

So I get rid of this warning and stop having a variable just flying around.


回答1:


Nope. I'd wrap it in a method somewhere to keep the noise out of the main flow:

  bool IsValidDate(string value)
  {
     DateTime result;
     return DateTime.TryParse(value, out result); //result is stored, but you only care about the return value of TryParse()
  }



回答2:


With C#7.0 (since August 2016) you can use the out var construct, and then just ignore the new var in subsequent code.

bool success = DateTime.TryParse(value, out var result);

If you truly do not care about the value of the result, use discards:

bool success = DateTime.TryParse(value, out _);



回答3:


I'm not suggesting you actually do this, but you could use a single helper class to make this easy for all out parameters:

public static class OutHelper<T>
{
    [ThreadStatic]
    public static T Ignored;
}

Then you can call:

if (DateTime.TryParse(text, out OutHelper<DateTime>.Ignored))

It's horrible, uses a public mutable field, and if your application is also executing with some malicious code, it gives that code access to the last value you've parsed... but it should work :)




回答4:


No. You can't get rid of the variable but you shouldn't get a compiler warning either.

Passing a variable as out is "using" the variable. The compiler will not issue a warning because of that.




回答5:


If you are using .NET 3 and above, you could always create an Extension method?

public static bool IsValidDate(this string value)
{
  DateTime date = DateTime.Null;
  return DateTime.TryParse(value, out date);
}

[Edited to rename the method name to a more appropriate one]




回答6:


TryParse is a better option. Its just a variable that is wasted. Other options include using the Convert.ToDateTime() within a try-catch block. But again that would not be efficient because try-catch blocks are meant to be heavy. The next option is regex. This is a better solution. I guess this gives you the result instantly than compared to the others.

You can very well wrap the method like Kim Gräsman said...



来源:https://stackoverflow.com/questions/1414469/null-out-parameters-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!