2012-02-05 92 views
0

我有一个字符串类的自定义实现。我在字符串和类之间添加了自定义转换运算符,并且投射正常工作。但是,如果我第一次将自定义对象转换为System.Object,然后将其转换为字符串:“无法将类型'MyString'转换为键入'System.String'”。这是为什么?我怎样才能使它...C#与转换运算符铸造

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! 
    } 
} 
+0

这是一个明确的演员。如果定义了隐式转换,则没有明确的运算符 – 2012-02-05 17:28:00

+0

显式转换工作。 – nogola 2012-02-05 17:31:07

回答

6

转换这样必须在编译时来确定 - 而在你的最后一行,的o编译时类型只是object,所以编译器没有按't'知道'你的转换作为一种选择。

除了仅仅说“不这样做”之外,很难知道最佳解决方案 - 如果您使用dynamic而不是object(当然,您使用的是C#4),那么它将工作 - 但我个人只会尝试而不是依赖于像这样的用户定义的转换。他们让代码库很难理解,IMO。

任何阅读表达(string) o其中o只是object期望这是一个简单的演员,即一个,如果o没有实际上是指一个字符串(或者是一个空引用),这将失败。试图找到混淆期望的方法是一个糟糕的主意,国际海事组织。

3

我会在班上覆盖ToString。然后用o.ToString()代替(string)o