20

これの疑わしい有用性とは別に、私はこれらの線に沿って何かをすることが可能かどうか尋ねたいと思います。

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;

プロパティを使用してプリミティブ型をカスタムクラスにラップし、getandsetメソッドに検証などの他のことを実行させるのが好きです。
私はこれを頻繁に行っているので、標準のプリミティブのように、より単純な構文もあればよいと思いました。
それでも、これは実現可能ではないだけでなく、概念的にも間違っている可能性があると思います。どんな洞察も大歓迎です、ありがとう。

4

2 に答える 2

41

値型(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が完全に正しいため、構造体を不変にしました。

于 2009-05-06T21:35:21.860 に答える
2

暗黙のキャストを使用できます。推奨されていませんが、次のようになります。

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

繰り返しますが、悪い習慣です。

于 2009-05-06T21:36:27.957 に答える