How do I allow my class to be implicitly converted to a string in C#?
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
&hell开发者_如何学编程ip; somehow…
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
string b = a.ToHtml();
But it's certainly possible...
public class A
{
public string Content { get; set; }
public static implicit operator string(A obj)
{
return string.Concat("<span>", obj.Content, "</span>");
}
}
To give an example of why I do not recommend this, consider the following:
var myHtml = "<h1>" + myA + "</h1>";
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:
var myHtml = string.Format("<h1>{0}</h1>", myA);
But string.Format
internally calls ToString
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>"
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";
}
overriding ToString() would be nice way. Moreover in debug mode you got a tip with ToString() return value.
精彩评论