除了这个问题有用之外,我想问一下是否可以按照这些方式做点什么。

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 方法执行其他操作,例如验证。
因为我经常这样做,所以我认为有一个更简单的语法,比如标准基元,这样会很好。
尽管如此,我怀疑这不仅不可行,而且在概念上也可能是错误的。 任何见解都会受到欢迎,谢谢。

有帮助吗?

解决方案

使用值类型( 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;
    }
}

编辑:使结构不可变,因为Marc Gravell绝对正确。

其他提示

您可以使用隐式投射。不推荐,但是:

public static implicit operator string(MyString a) {
    return a.Value;
}
public static implicit operator MyString(string a) {
    return new MyString { value = a; }
}

再次,糟糕的做法。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top