C# 中的自定义原语?
除了这个有用性值得怀疑之外,我想问是否可以沿着这些思路做一些事情。
class MyPrimitive {
String value;
public String Value {
get { return value; }
set { this.value = value; }
}
}
// Instead of doing this...
MyPrimitive a = new MyPrimitive();
a.Value = "test";
String b = a.Value;
// Isn't there a way to do something like this?
MyPrimitive a = "test";
String b = a;
我喜欢使用属性将原始类型包装到自定义类中,以使 get
和 set
方法执行其他操作,例如验证。
因为我经常这样做,所以我认为最好也有一个更简单的语法,就像标准原语一样。
尽管如此,我怀疑这不仅不可行,而且在概念上也可能是错误的。 任何见解都将受到欢迎,谢谢。
Apart from the questionable usefulness of this, I'd like to ask if it is possible to do something along these lines.
class MyPrimitive {
String value;
public String Value {
get { return value; }
set { this.value = value; }
}
}
// Instead of doing this...
MyPrimitive a = new MyPrimitive();
a.Value = "test";
String b = a.Value;
// Isn't there a way to do something like this?
MyPrimitive a = "test";
String b = a;
I like to wrap primitive types into custom classes using a property to make the get
and set
method perform other things, like validation.
Since I'm doing this quite often I thought that it'd be nice to also have a simpler syntax, like for the standard primitives.
Still, I suspect that this not only isn't feasible but could also be conceptually wrong.
Any insights would be most welcome, thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用值类型 (
struct
) 并为其赋予隐式转换运算符来自您想要在赋值右侧的类型。编辑:使结构不可变,因为 Marc Gravell 是绝对正确的。
Use a value type (
struct
) and give it an implicit conversion operator from the type you want on the right hand side of assignment.EDIT: Made the struct immutable because Marc Gravell is absolutely right.
您可以使用隐式转换。 不推荐这样做,但是:
同样,这是不好的做法。
You could use implicit casting. It's not recommended, but:
Again, bad practice.