我有一個容器類,用於向int,string等標準數據類型添加一些屬性。這個容器類封裝了這樣一個(標準類型)對象的對象。 其他類然後使用容器類的子類來獲取/設置添加的屬性。現在我希望子類可以隱式地在它的封裝對象和自身之間進行轉換,而不需要額外的代碼。如何在C#3.5的超類中定義cast運算符?
這是我的類的一個簡化的例子:
// Container class that encapsulates strings and adds property ToBeChecked
// and should define the cast operators for sub classes, too.
internal class StringContainer
{
protected string _str;
public bool ToBeChecked { get; set; }
public static implicit operator StringContainer(string str)
{
return new StringContainer { _str = str };
}
public static implicit operator string(StringContainer container)
{
return (container != null) ? container._str : null;
}
}
// An example of many sub classes. Its code should be as short as possible.
internal class SubClass : StringContainer
{
// I want to avoid following cast operator definition
// public static implicit operator SubClass(string obj)
// {
// return new SubClass() { _str = obj };
// }
}
// Short code to demosntrate the usings of the implicit casts.
internal class MainClass
{
private static void Main(string[] args)
{
SubClass subClass = "test string"; // ERROR: Cannot convert source type 'string' to 'SubClass'
string testString = subClass; // No error
}
}
我的真容器類有兩個類型參數,一個用於封裝的對象的類型(字符串,整數,...)和用於第二子類型(例如SubClass)。
我怎樣才能使代碼
SubClass subClass = "test string"; // ERROR: Cannot convert source type 'string' to 'SubClass'
可運行在子類最少的代碼?
你爲什麼這樣做?如果要爲現有的基礎數據類型添加功能,那麼爲什麼不使用擴展方法? – 2010-10-07 16:38:30
我沒有得到這個設計.. – vulkanino 2010-10-07 16:41:03
@George Stocker:我需要擴展屬性,因爲我需要將數據保存到封裝對象。 – Markus 2010-10-07 16:47:11