如何允许我的类隐式转换为 C# 中的字符串?
这就是我想要做的...
public class A
{
public string Content { get; set; }
}
A a = new A();
a.Content = "Hello world!";
string b = a; // b now equals "<span>Hello world!</span>"
所以我想控制 如何 a
转换为 String
...不知何故...
Here's what I want to do...
public class A
{
public string Content { get; set; }
}
A a = new A();
a.Content = "Hello world!";
string b = a; // b now equals "<span>Hello world!</span>"
So I want to control how a
is converted into a String
… somehow…
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以手动覆盖类的隐式和显式强制转换运算符。 教程在这里。不过,我认为大多数时候它的设计很糟糕。我想说,如果你写的话会更容易看到发生了什么
但这当然是可能的...
为了给出一个为什么我不推荐这样做的例子,请考虑以下内容:
上面的将产生
"
; Hello World!
"
现在,其他一些开发人员出现并认为上面的代码看起来很糟糕,并将其重新格式化为以下内容:
但是
string.Format
在内部为它接收到的每个参数调用ToString
,因此我们不再处理隐式转换,因此,其他开发人员将把结果更改为类似于“
myNamespace.A
”
You can manually override the implicit and explicit cast operators for a class. Tutorial here. I'd argue it's poor design most of the time, though. I'd say it's easier to see what's going on if you wrote
But it's certainly possible...
To give an example of why I do not recommend this, consider the following:
The above will, yield
"<h1><span>Hello World!</span></h1>"
Now, some other developer comes along and thinks that the code above looks poor, and re-formats it into the following:
But
string.Format
internally callsToString
for every argument it receives, so we're no longer dealing with an implicit cast, and as a result, the other developer will have changed the outcome to something like"<h1>myNamespace.A</h1>"
重写 ToString() 是个好方法。此外,在调试模式下,您会得到有关 ToString() 返回值的提示。
overriding ToString() would be nice way. Moreover in debug mode you got a tip with ToString() return value.