除了这个问题的可疑性之外,我想问一下是否有可能沿着这些方向做点什么.
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;
Run Code Online (Sandbox Code Playgroud)
我喜欢使用属性将原始类型包装到自定义类中,以使get和set方法执行其他操作,例如验证.
因为我经常这样做,所以我认为使用更简单的语法会更好,就像标准基元一样.
尽管如此,我怀疑这不仅不可行,而且在概念上也可能是错误的.任何见解都会受到欢迎,谢谢.
Nei*_*ams 34
使用值类型(struct)并从赋值右侧所需的类型中为其提供隐式转换运算符.
struct MyPrimitive
{
private readonly string value;
public MyPrimitive(string value)
{
this.value = value;
}
public string Value { get { return value; } }
public static implicit operator MyPrimitive(string s)
{
return new MyPrimitive(s);
}
public static implicit operator string(MyPrimitive p)
{
return p.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:使结构不可变,因为马克格拉维尔是绝对正确的.
| 归档时间: |
|
| 查看次数: |
3898 次 |
| 最近记录: |