这就是我想做的...
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
……不知何故……
这就是我想做的...
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
……不知何故……
您可以手动覆盖类的隐式和显式转换运算符。教程在这里。不过,我认为大多数时候这是糟糕的设计。我会说如果你写的话更容易看到发生了什么
string b = a.ToHtml();
但这肯定是可能的...
public class A
{
public string Content { get; set; }
public static implicit operator string(A obj)
{
return string.Concat("<span>", obj.Content, "</span>");
}
}
为了举例说明我为什么不推荐这样做,请考虑以下几点:
var myHtml = "<h1>" + myA + "</h1>";
以上将,产量"<h1><span>Hello World!</span></h1>"
现在,其他一些开发人员出现并认为上面的代码看起来很糟糕,并将其重新格式化为以下内容:
var myHtml = string.Format("<h1>{0}</h1>", myA);
但是在string.Format
内部调用ToString
它收到的每个参数,因此我们不再处理隐式转换,结果,其他开发人员会将结果更改为类似"<h1>myNamespace.A</h1>"
public class A
{
public string Content { get; set; }
public static implicit operator string(A a)
{
return string.Format("<span>{0}</span>", a.Content);
}
}
public static implicit operator string(A a)
{
return "foo";
}
覆盖 ToString() 将是一个不错的方法。此外,在调试模式下,您会得到一个 ToString() 返回值的提示。