【发布时间】:2010-10-07 16:31:33
【问题描述】:
我有一个容器类,用于向标准数据类型(如 int、string 等)添加一些属性。这个容器类封装了这样一个(标准类型)对象的对象。 然后其他类使用容器类的子类来获取/设置添加的属性。现在我希望子类可以在其封装的对象和自身之间隐式转换,而不需要额外的代码。
这是我的课程的简化示例:
// 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
}
}
我的真实容器类有两个类型参数,一个用于封装对象的类型(字符串、int、...),第二个用于子类类型(例如 SubClass)。
如何制作代码
SubClass subClass = "test string"; // ERROR: Cannot convert source type 'string' to 'SubClass'
可通过子类中的最少代码运行?
【问题讨论】:
-
你为什么要这样做?如果是为现有的基本数据类型添加功能,那为什么不使用扩展方法呢?
-
@George Stocker:我需要扩展属性,因为我需要将数据保存到封装对象中。
-
@vulkanino:对不起。解释为什么我需要一个如此棘手的设计并不容易。我试图解释。我有用于填充我的“被测对象”的测试数据对象。测试后我想检查结果是否符合我的预期。因此,我在所有应该检查的测试数据对象上设置了属性 ToBeChecked,并调用了一个检查方法,该方法将测试数据对象作为参数。该检查方法仅检查具有 ToBeChecked==true 的这些测试数据对象。那是更广泛的背景。我可以用正常的设计做所有事情。
-
@vulkanino 继续:几乎我所有的测试数据对象都有一些字符串、int 等类型的成员。这些成员还需要 ToBeChecked 属性。因此我将它封装在一个容器类中。现在我不想为每个成员容器编写太多代码。所以我正在寻找一个没有太多代码的解决方案。我目前的解决方案是定义一个容器基类来实现我需要的所有属性,并为每个测试数据成员定义一个子类。
标签: c# casting operator-keyword