How Can I inherit the string class?

后端 未结 7 2123
春和景丽
春和景丽 2020-12-03 10:03

I want to inherit to extend the C# string class to add methods like WordCount() and several many others but I keep getting this error:

Er

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 11:03

    Another option could be to use an implicit operator.

    Example:

    class Foo {
        readonly string _value;
        public Foo(string value) {
            this._value = value;
        }
        public static implicit operator string(Foo d) {
            return d._value;
        }
        public static implicit operator Foo(string d) {
            return new Foo(d);
        }
    }
    

    The Foo class acts like a string.

    class Example {
        public void Test() {
            Foo test = "test";
            Do(test);
        }
        public void Do(string something) { }
    }
    

提交回复
热议问题