加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在C#3.5中定义超类中的强制转换操作符?

发布时间:2020-12-16 06:54:55 所属栏目:百科 来源:网络整理
导读:我有一个容器类,用于向标准数据类型添加一些属性,如int,string等.此容器类封装了此类(标准类型)对象的对象. 然后,其他类使用容器类的子类来获取/设置添加的属性.现在我希望子类可以隐式地在它的封装对象和它自己之间进行转换,而不需要额外的代码. 这是我的类
我有一个容器类,用于向标准数据类型添加一些属性,如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
    }
  }

我的真实容器类有两个类型参数,一个用于封装对象的类型(string,int,…),另一个用于子类类型(例如SubClass).

我该如何制作代码

SubClass subClass = "test string"; // ERROR: Cannot convert source type 'string' to 'SubClass'

可以通过子类中的最小代码运行吗?

解决方法

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读