Pregunta

Además de la cuestionable utilidad de esto, me gustaría preguntar si es posible hacer algo en este sentido.

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;

Me gusta incluir tipos primitivos en clases personalizadas utilizando una propiedad para hacer que el método get y set realice otras cosas, como la validación.
Como hago esto con bastante frecuencia, pensé que sería bueno tener también una sintaxis más simple, como las primitivas estándar.
Aún así, sospecho que esto no solo no es factible sino que también podría ser conceptualmente incorrecto. Cualquier idea sería bienvenida, gracias.

¿Fue útil?

Solución

Utilice un tipo de valor ( struct ) y asígnele un operador de conversión implícita del tipo que desea en el lado derecho de la asignación.

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;
    }
}

EDITAR: hizo que la estructura sea inmutable porque Marc Gravell tiene toda la razón.

Otros consejos

Puede usar conversión implícita . No se recomienda, pero:

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

Nuevamente, mala práctica.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top