c# – 我可以在结构体上创建访问器来自动转换到其他数据类型吗?
发布时间:2020-12-15 06:48:59 所属栏目:百科 来源:网络整理
导读:是否可以做如下的事情: struct test{ this { get { /*do something*/ } set { /*do something*/ } }} 所以如果有人试图这样做, test tt = new test();string asd = tt; // intercept this and then return something else 解决方法 从概念上讲,你在这里做的
是否可以做如下的事情:
struct test { this { get { /*do something*/ } set { /*do something*/ } } } 所以如果有人试图这样做, test tt = new test(); string asd = tt; // intercept this and then return something else 解决方法
从概念上讲,你在这里做的事情实际上是可以在.NET和C#中进行的,但是你在语法方面咆哮着错误的树.看来这个
implicit conversion operator会是这个解决方案,
例: struct Foo { public static implicit operator string(Foo value) { // Return string that represents the given instance. } public static implicit operator Foo(string value) { // Return instance of type Foo for given string value. } } 这允许您为自定义类型的对象(/ Foo)分配和返回字符串(或任何其他类型). var foo = new Foo(); foo = "foobar"; var string = foo; // "foobar" 当然,这两个隐式转换运算符不一定对称,尽管通常是可取的. 注意:还有 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容