测试 NULL 和 NULL如果需要,返回一个字符串 - 优点/缺点是什么
我有一个简单的类,它实现了 ToString
,我对内容很满意。我试图通过查看各种选项是否有任何优点/缺点来决定什么是(最)正确的方法。
对于下面的示例:
- 类:
Astronaut
- 类型变量
Astronaut
:person
我在这里滚雪球的选项:
string result =人==空? “未知宇航员”:person.ToString();
string result = person.ToString() ?? "未知宇航员";
string result = (person ?? "Unknown Astronaut").ToString();
string result = person ?? (object)"Unknown Astronaut";
我对这些的看法
- 非常冗长&我不需要那么冗长。
- 比 1 好得多,但是
ToString
感觉很丑,而且担心ToString
代码中出现异常。 - 这似乎很受欢迎(此处 & 此处),但我不确定它是否有效。编译器不会抱怨
string
& 吗?Astronaut
类型不是同一类型,因此不能在合并中使用。 - 这是我现在最满意的,但它意味着一个盒子和一个盒子。
ToString
应该person
为空。
总结:
- 上述任何一项有优点/缺点吗?
- 你能想到什么选择吗?
I have a simple class which has a ToString
implemented which I am happy with the content. I am trying to decide what is the (most) correct way by seeing if there are any pro's/con's for the various options.
For the example below:
- Class:
Astronaut
- Variable of type
Astronaut
:person
Options that I am just snow balling here:
string result = person == null ? "Unknown Astronaut" : person.ToString();
string result = person.ToString() ?? "Unknown Astronaut";
string result = (person ?? "Unknown Astronaut").ToString();
string result = person ?? (object)"Unknown Astronaut";
My views on those are
- Very verbose & I don't need that level of verbosity.
- Much better than 1 but the
ToString
feels ugly plus worried of exceptions in thatToString
code. - This seems popular (here & here) but I am not sure it will work. Won't the compiler complain about a
string
& aAstronaut
type not being the same type and thus can not be used in a coalese. - This is the one I am happiest with now, but it means a box &
ToString
shouldperson
be null.
In summary:
- Any pro's/con's to any of the above?
- Any options you can think of?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我更喜欢扩展方法:
所以对于你的问题:
I prefer an extension method:
So to your question:
创建一个静态
ToString
方法,然后像这样调用它:提取通用代码的最佳方法。
Create a static
ToString
method and just call it like:Best way to factor out common code.
我记得一本设计模式书告诉我一些实例化的对象,其唯一目的是填充空对象。它们会返回名称的空字符串、长度的 0 等等。听起来不是一个坏主意。
您还可以将其实现为 Astronaut 类的静态方法:
I remember a design patterns book telling me about some object that you instantiate for the sole purpose of filling in null objects. They would return things like the empty string for name, or 0 for length, and so on. Doesn't sound like a bad idea.
You could also implement it as a static method of the
Astronaut
class:您还可以在类中放置一个静态方法,将 Astronaut 转换为字符串,或者在参数为 null 时返回“Unknown astronaut”。
同样,您可以将其设为扩展方法并直接在该类型的变量上调用它,即使它为 null。
You could also place a static method in the class that converts an Astronaut to string or returns "Unknown astronaut" if the argument was null.
In a similar vein, you could make it an extension method and call it directly on a variable of that type, even if it's null.