【问题标题】:How to define cast operator in super class in C# 3.5?如何在 C# 3.5 的超类中定义强制转换运算符?
【发布时间】: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


【解决方案1】:

我认为没有办法在基类中定义转换运算符。

基类对子类一无所知,因此没有足够的信息来构造它。例如,如果您的 SubClass 类型只有一个需要一些参数的构造函数怎么办?基类不知道子类,所以不能以任何方式构造它。

也许您可以使用另一种方法来参数化StringContainer 类型。例如,您可以将一些函数(Func<...> 类型的委托)传递给StringContainer 类,而不是使用实现继承(子类)。这样,用户可以对类进行参数化,而您的隐式转换仍然有效。

【讨论】:

  • @base 类对子类一无所知:我可以为子类类型设置类型参数。例如。内部类 StringContainer
  • @Markus:理论上,使用类型参数是一种解决方案,但我认为 C# 不允许您编写 public static implicit operator T(..) 其中T 是类型参数。
  • 谢谢托马斯。我想我会使用解决方法来不使用子类。
猜你喜欢
  • 2012-03-29
  • 1970-01-01
  • 2018-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-03
  • 2018-03-18
相关资源
最近更新 更多