C#中的自定义原语?

16 c# primitive

除了这个问题的可疑性之外,我想问一下是否有可能沿着这些方向做点什么.

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)

我喜欢使用属性将原始类型包装到自定义类中,以使getset方法执行其他操作,例如验证.
因为我经常这样做,所以我认为使用更简单的语法会更好,就像标准基元一样.
尽管如此,我怀疑这不仅不可行,而且在概念上也可能是错误的.任何见解都会受到欢迎,谢谢.

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)

编辑:使结构不可变,因为马克格拉维尔是绝对正确的.

  • 如果你把它作为一个结构,你应该**绝对**同时使它不可变; 在结构上有一个{get; set;}是一个非常非常糟糕的主意.我提到了这个坏事吗? (6认同)
  • 这正是提问者正在寻找的。它不完全是一个“自定义原语”,但它尽可能地模仿一个,并且是 C# 中的正确方法。 (2认同)