是否有一个内置的类型在C#中包含一个布尔值和一个字符串的静态方法的返回?字符串、静态、有一个、类型

2023-09-05 01:02:56 作者:会推开就别靠近我

我在找一个类型从一个函数或方法返回,首先传达,无论是成功还是失败,然后武官消息(字符串),它通过对失败的原因的详细信息。它可能是在应用程序退出code线;但是,我不建立了一整套的出口codeS的索引一个特定的错误消息。我喜欢的一个成功退出code中的想法,以便人们可以快速检查调用是否失败与否,并相应工作。

我想使这个一系列的静态方法(如服务调用)的返回类型,并且我可以只创建一个类与这两个领域(布尔和字符串);不过,我觉得像这些可能已经存在,但我一直没能找到它。此外,如果要处理来自一个方法的返回来获得这样的信息,或对这些类静态类的完全一般而言更好的实践,我欢迎您的意见。

有关更好的显示效果:

 公共静态<类型> CreateSomething(字符串somethingName)
    {
        ...
        返回全新<类型>(失败!,因为......);
    }
 

解决方案 C 初学者教程系列4 C 数据类型示例,int double string

有两个明显的方法是:定义自己的类型或使用元组LT; T1,T2>

我认为,你应该总是只定义自己的类型。它不用花一分钱。去做就对了。这就是你的意思去做。

如果你觉得特别懒,但...

 公开元组LT;布尔,字符串>的MyMethod(...)
{
    ...
    返回Tuple.Create(假的,有些事情打破了);
}
 

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...");
    }

解决方案

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");
}

 
精彩推荐
图片推荐