简体   繁体   中英

How to get the custom attribute of a const string contained in struct in static class

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..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM