C#使用转换运算符进行转换

nog*_*ola 0 c# casting implicit-conversion

我有一个字符串类的自定义实现.我在字符串和类之间添加了自定义转换运算符,并且转换正常.但是,如果我首先将自定义对象转换为System.Object然后转换为字符串,则说:"无法将类型'MyString'强制转换为'System.String'".这是为什么?我怎样才能启用它...

class MyString
{
    public string S {get; set;}

    public MyString(string s)
    {
        this.S = s;
    }

    public static implicit operator string(MyString s)
    {
        return s.S;
    }
    public static implicit operator MyString(string s)
    {
        return new MyString(s);
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyString ms = new MyString("a");
        string s = ms;
        object o = ms;
        string s1 = (string)o; // <-- this throws the exception!
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

像这样的转换必须在编译时确定- 而在最后一行中,编译时类型o只是object,因此编译器不会"知道"您的转换作为选项.

除了说"不要那样做"之外,很难知道问题的最佳解决方案 - 如果你使用dynamic而不是object(当然你使用的是C#4)那么它会起作用 - 但我个人认为尽量不要依赖这样的用户定义转换.它们使代码库很难理解,IMO.

任何阅读表达(string) o,其中o只是object想到这是一个简单的演员,也就是一个,如果它会失败o并没有实际上是指一个字符串(或者是一个空引用).IMO,试图找到混淆期望的方法是一个坏主意.