我有一个容器类,用于向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