I search a solution to get the custom attribute of a const string by the value of this const string. Like this example :
public static class Directory
{
public struct Bank01
{
[SymbolAttribute("Attribute01")]
public const string Value01 = "Bank01.Value01";
[SymbolAttribute("Attribute02")]
public const string Value02 = "Bank01.Value02";
}
public struct Bank02
{
[SymbolAttribute("Attribute03")]
public const string Value01 = "Bank02.Value01";
[SymbolAttribute("Attribute04")]
public const string Value02 = "Bank02.Value02";
}
public static SymbolAttribute GetSymbolAttribute(string value)
{
return typeof(Directory)
.GetMember(value.Split('.')[0])
.GetType()
.GetField(value.Split('.')[1])
.GetCustomAttribute<SymbolAttribute>();
}
}
I want use this function like this :
public static Main()
{
SymbolAttribute attribute = GetSymbolAttribute(Directory.Bank01.Value01);
}
I don't understand why this one work :
return typeof(Directory.Bank01)
.GetField(value.Split('.')[1])
.GetCustomAttribute<SymbolAttribute>();
And this one doesn't work :
return typeof(Directory)
.GetMember(value.Split('.')[0])
.GetType()
.GetField(value.Split('.')[1])
.GetCustomAttribute<SymbolAttribute>();
Do you have an idea ? Thank you in advance ..
CodePudding user response:
Bank01 and Bank02 are not members, they are nested classes, so you should use GetNestedType instead.
typeof(Directory)
.GetNestedType(value.Split('.')[0])
.GetField(value.Split('.')[1])
.GetCustomAttribute<SymbolAttribute>();
