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