如何允许我的类隐式转换为C#中的字符串?

jed*_*mao 4 c# implicit-conversion

这就是我想要做的......

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>"
Run Code Online (Sandbox Code Playgroud)

所以我想控制如何 a转换成String......不知怎的......

Dav*_*und 12

您可以手动覆盖类的隐式和显式转换运算符.这里的教程.不过,我认为它大部分时间都是糟糕的设计.我会说如果你写的话会更容易看到发生了什么

string b = a.ToHtml();
Run Code Online (Sandbox Code Playgroud)

但它肯定有可能......

public class A
{
    public string Content { get; set; }

    public static implicit operator string(A obj)
    {
        return string.Concat("<span>", obj.Content, "</span>");
    }
}
Run Code Online (Sandbox Code Playgroud)

举一个为什么我不推荐这个的例子,考虑以下内容:

var myHtml = "<h1>" + myA + "</h1>";
Run Code Online (Sandbox Code Playgroud)

以上会,屈服 "<h1><span>Hello World!</span></h1>"

现在,一些其他开发人员出现并认为上面的代码看起来很糟糕,并将其重新格式化为以下内容:

var myHtml = string.Format("<h1>{0}</h1>", myA);
Run Code Online (Sandbox Code Playgroud)

string.Format内部调用ToString它收到的每个参数,所以我们不再处理隐式转换,结果,其他开发人员将结果更改为类似"<h1>myNamespace.A</h1>"

  • @sfjedi:场景越复杂,隐式转换就越不合适,IMO.根据我的经验,有很少的地方可以让代码更清晰. (4认同)

des*_*sco 8

public class A
{
    public string Content { get; set; }
    public static implicit operator string(A a)
    {
        return string.Format("<span>{0}</span>", a.Content);
    }
}
Run Code Online (Sandbox Code Playgroud)