Lambda para getter y setter de la propiedad


En C # 6.0 puedo escribir:

public int Prop => 777;

Pero quiero usar getter y setter. ¿Hay alguna manera de hacer algo más o menos?

public int Prop {
   get => propVar;
   set => propVar = value;
}
 25
Author: Stijn, 2016-04-02

3 answers

En primer lugar, eso no es lambda, aunque la sintaxis es similar.

Se llama " miembros con cuerpo de expresión". Son similares a lambdas, pero aún así fundamentalmente diferentes. Obviamente no pueden capturar variables locales como lo hacen las lambdas. Además, a diferencia de lambdas, son accesibles a través de su nombre:) Probablemente entenderás esto mejor si intentas pasar una propiedad con cuerpo de expresión como delegado.

No existe una sintaxis de este tipo para los setters en C # 6.0, pero C # 7.0 lo introduce .

private int _x;
public X
{
    get => _x;
    set => _x = value;
}
 50
Author: Diligent Key Presser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-17 21:50:25

C # 7 trae soporte para setters, entre otros miembros:

Más expresión miembros con cuerpo

Métodos con cuerpo de expresión, propiedades, etc. son un gran éxito en C# 6.0, pero no los permitimos en todo tipo de miembros. C# 7.0 añade accessors, constructors and finalizers to the list of things that can tener cuerpos de expresión:

class Person
{
    private static ConcurrentDictionary<int, string> names = new ConcurrentDictionary<int, string>();
    private int id = GetId();

    public Person(string name) => names.TryAdd(id, name); // constructors
    ~Person() => names.TryRemove(id, out _);              // finalizers
    public string Name
    {
        get => names[id];                                 // getters
        set => names[id] = value;                         // setters
    }
}
 24
Author: Stijn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-09 13:36:27

No existe tal sintaxis, pero la sintaxis más antigua es bastante similar:

    private int propVar;
    public int Prop 
    {
        get { return propVar; }
        set { propVar = value; }
    }

O

public int Prop { get; set; }
 2
Author: Marcin Iwanowski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-02 11:17:49