Is it possible to assign the default value of a property with an attribute?

3

I'd like to be able to declare a property as:

[DefaultValue(10)]
public int Maximo { get; set; }

And when it was used, it already came with the value started in 10 . However the attribute does not assign the value, when I try to use:

public void FazAlgo()
{
    int max = Maximo; // 0
}

The value comes from 0 , which is the integer pattern.

An alternative would be to create a field and implement get and set , but I'm looking for a way to do this without having to implement the methods.

I would like to do with attributes the way I have exemplified, is it possible? How?

    
asked by anonymous 23.12.2013 / 03:27

2 answers

3

The DefaultValue attribute , as stated in the specification, does not in itself change the value of the property. It is meant to be used by the design editor and code generators.

You can use Reflection

in> (note that reflection has / (may have) a performance cost, not recommended to override trivial assignments) to start properties, the following extension method gets all class properties and checks by the DefaultValue attribute, if it finds it it gets the value of the attribute and assigns the property.

public static class Extensoes
{
    // método de extensão para 'Object', funcionando assim em
    // todas classes
    public static void InicializaValores(this Object o)
    {
        // obtem todas propriedades, campos...
        var propriedades = o.GetType()
            .GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

        // para cada propriedade
        foreach (var propriedade in propriedades)
        {
            // pega o atributo DefaultValue
            var atributos = propriedade
                .GetCustomAttributes(typeof(DefaultValueAttribute), true)
                .OfType<DefaultValueAttribute>().ToArray();

            // se encontrou
            if (atributos != null && atributos.Length > 0)
            {
                // pega o atributo
                var atributoValorPadrao = atributos[0];

                // seta o valor da propriedade do objeto o
                // para o valor do atributo
                propriedade.SetValue(o, atributoValorPadrao.Value, null);
            }
        }
    }
}

With this method to read the value of the attributes and associate with the property, you still need to invoke the method.

This can be done in the class constructor, for example:

public class Teste
{
    [DefaultValue(10)]
    public int Maximo { get; set; }

    public int Minimo { get; set; }

    public Teste()
    {
        this.InicializaValores();
    }
}

Testing:

static class Program
{
    static void Main(string[] args)
    {
        var test = new Teste();

        // poderia ser feito aqui também
        //test.InicializaValores();

        Console.WriteLine(test.Maximo); // 10
        Console.WriteLine(test.Minimo); // 0

        Console.ReadKey();
    }
}
    
23.12.2013 / 03:27
1
public int Maximo { get; set; } = 10 
// Somente na versão do .NET mais nova, não sei qual exatamente

Or, ugly but simplistic:

public bool _maximoFoiAlterado;
public int _maximo;
public int Maximo 
{ 
get
{
    if (!_maximoFoiAlterado) return 10;
    else return _maximo;
}
set
{
    _maximoFoiAlterado = true;
    _maximo = value;
}
}
    
15.02.2016 / 16:25