Initializing fields through attribute?
I want the value to be initialized according to the attribute When Instance is created.
class FieldAttr : Attribute
{
public readonly string key;
public Key_FieldAttr(string key)
{
this.key = key;
}
}
class CtorAttr : Attribute
{
}
static string FromTable(string key)
{
// will return localized string of key from table.
}
...
class LocalizedMetadata
{
[FieldAttr("NAME")]
public string Name { get; }
[FieldAttr("DESC")]
public readonly string Description;
[CtorAttr]
public LocalizedMetadata(string header)
{
// I want "Key" attribute to do as below...
// this.Name = FromTable(header + "NAME");
// this.Description = FromTable(header + "DESC");
}
}
public static void Main(string[] args)
{
var foo = new LocalizedMetadata("UNITY_");
Console.WriteLine(foo.Name); // = FromTable("UNITY_NAME");
Console.WriteLine(foo.Description); // = FromTable("UNITY_DESC");
}
I don't know where to attach what kind of Attribute (Field, Construction, Class) will be possible. I looked up documents about Attribute and Reflection, but I don't know if this is possible.
I think below solution will solve your problem.
class LocalizedMetadata
{
[FieldAttr("NAME")]
public string Name { get; set; }
[FieldAttr("DESC")]
public string Description { get; set; }
public LocalizedMetadata(string header)
{
foreach (var property in typeof(LocalizedMetadata).GetProperties())
{
foreach (var attr in property.GetCustomAttributes(false))
{
FieldAttr fieldAttr = (FieldAttr)attr;
property.SetValue(this, header + fieldAttr.Key);
}
}
}
}
public static void Main(string[] args)
{
var foo = new LocalizedMetadata("UNITY_");
Console.WriteLine(foo.Name);
Console.WriteLine(foo.Description);
}
Output:
UNITY_NAME
UNITY_DESC