2010-10-07 24 views
4

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

可运行在子类最少的代码?

+0

你为什么这样做?如果要为现有的基础数据类型添加功能,那么为什么不使用扩展方法? – 2010-10-07 16:38:30

+2

我没有得到这个设计.. – vulkanino 2010-10-07 16:41:03

+0

@George Stocker:我需要扩展属性,因为我需要将数据保存到封装对象。 – Markus 2010-10-07 16:47:11

回答

1

我不认为有一种方法可以在基类中定义转换运算符。

基类不知道子类的任何内容,所以它没有足够的信息来构造它。例如,如果​​类型只有一个需要某些参数的构造函数会怎么样?基类不知道子类,所以它不能以任何方式构造它。

也许你可以用另一种方法来参数化StringContainer类型。例如,您可以不使用实现继承(子类),而是将某些函数(Func<...>类型的代理)传递给StringContainer类。这样,用户可以参数化类,并且您的隐式转换仍然可以工作。

+0

@base类不知道有关子类的任何信息:我可以为子类类型设置一个类型参数。例如。内部类StringContainer Markus 2010-10-07 16:48:26

+0

@Markus:理论上,使用类型参数是一个解决方案,但我不认为C#将允许您编写“公共静态隐式运算符T(..)”,其中“T”是一种类型参数。 – 2010-10-07 18:52:51

+0

谢谢Tomas。我想我会使用这个工作来不使用子类。 – Markus 2010-10-08 07:31:57