问题
I'm looking for a type to return from a function or method, to convey first, whether it was successful or not, and then attache a message (as a string) to it to pass further information about why it failed. It might be something on the lines of an Application Exit Code; however, I don't to create a whole set of exit codes to index a particular error message. I do like the idea of a single "success" exit code so one can quickly check whether the call failed or not and work accordingly.
I wanted to make this the return type of a series of static methods (like service calls), and for which I could just create a class with those two fields (bool and string); however, I feel something like these might exist already, although I haven't been able to find it. Also, if there are better practices to handling the return from a method to obtain this sort of info, or a general rule against these sort of static classes altogether, I welcome your comments.
For better visualization:
public static <type> CreateSomething(string somethingName)
{
...
return new <type>("Fail!", "Because...");
}
回答1:
There are two obvious approaches to this: define your own type or use Tuple<T1, T2>
.
I would argue that you should almost always just define your own type. It costs nothing. Just do it. That’s how you’re meant to do it.
If you’re feeling particularly lazy though...
public Tuple<bool, string> MyMethod(...)
{
...
return Tuple.Create(false, "Something broke");
}
回答2:
Instead of creating a new type you can follow the TryDoSomething pattern in the .NET framework.
For example:
int number;
if(Int32.TryParse(value, out number))
{
Console.WriteLine(number);
}
You can create a method that returns a boolean to signal success or failure. It can also return out parameters for an error message.
回答3:
What you are talking about is called generics. Here is the Microsoft intro to generics, and there is plenty online about them, also.
More to your question, also, you can combine generics with the TryCan pattern. However, often times you will want to just bubble an exception, so think this through properly
回答4:
It's an Exception.
Your function should not return a true/false for success. It should be a void that throws an exception if it fails.
...And don't forget to put the exception in the XML comments of the method.
回答5:
The core assemblies of .net don't contain such a type. You can find Option<T>
in the F# runtime.
I also posted such a type in an older question on SO: Generic property disadvantages?
来源:https://stackoverflow.com/questions/9811398/is-there-a-built-in-type-in-c-sharp-that-contains-a-bool-and-a-string-for-static