繁体   English   中英

C#中的自定义原语?

[英]Custom primitives in 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;

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

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

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

你可以使用隐式转换 不建议这样做,但是:

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM