1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
using System.ComponentModel;
using System.Reflection;
namespace gfoidl.Tools
{
public class AutomaticProperties
{
/// <summary>
/// Weist die Standardwerte den Eigenschaften zu.
/// </summary>
/// <param name="o">
/// Die Klasse bzw. die Instanz davon dessen Eigenschaften
/// gesetzt werden soll
/// </param>
public virtual void InitDefaults(object o)
{
// Alle Eigenschaften holen:
PropertyInfo[] propteryInfos =
o.GetType().GetProperties(
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.Static);
// Alle Eigenschaften durchlaufen:
foreach (PropertyInfo pi in propteryInfos)
{
// Nur wenn ein Attribut gesetzt ist:
if (pi.GetCustomAttributes(true).Length > 0)
{
// Attribute holen:
object[] attributes =
pi.GetCustomAttributes(
typeof(DefaultValueAttribute),
true);
if (attributes != null)
{
// Das 1. Attribut holen:
DefaultValueAttribute dva =
attributes[0] as DefaultValueAttribute;
if (dva != null)
pi.SetValue(o, dva.Value, null);
}
}
}
}
//---------------------------------------------------------------------
/// <summary>
/// Der Konstruktor wird immer als ersters aufgerufen wenn von dieser
/// Klasse abgeleitet wird!
/// </summary>
public AutomaticProperties()
{
InitDefaults(this);
}
}
}
|