2010-01-24 73 views
8

考慮下面的代碼:使用字符串常量

public class TextType { 

    public TextType(String text) { 
     underlyingString = text; 
    } 

    public static implicit operator String(TextType text) { 
     return text.underlyingString; 
    } 

    private String underlyingString; 
} 

TextType text = new TextType("Something"); 
String str = text; // This is OK. 

但我希望能做到以下幾點,如果可能的話。

TextType textFromStringConstant = "SomeOtherText"; 

我不能延伸與TextType隱含運算符重載String類,但沒有任何的方式來分配一個文字串到另一個類(其通過一種方法或東西處理)?

字符串是一個引用類型,所以當他們開發C#時,他們顯然必須使用某種方式來獲取字符串文本到類中。我只是希望它不會被硬編碼到語言中。

+0

詳情請參閱第10.10.3節。 – 2010-01-24 20:13:38

回答

9
public static implicit operator TextType(String text) { 
    return new TextType(text); 
} 
+0

修復文本!=值 - 你的速度雖然:) – 2010-01-24 18:49:27

+1

我不能相信我是如何錯過運營商超載兩種方式。我有一種感覺,該方法將不得不屬於字符串類... 謝謝。 – 2010-01-24 18:54:27

6

添加

public static implicit operator TextType(string content) { 
    return new TextType(content); 
} 

上您的課? :)