Reflection - get attribute name and value on property

后端 未结 15 2061
谎友^
谎友^ 2020-11-22 04:59

I have a class, lets call it Book with a property called Name. With that property, I have an attribute associated with it.

public class Book
{
    [Author(\"         


        
15条回答
  •  醉梦人生
    2020-11-22 05:17

    to get attribute from enum, i'm using :

     public enum ExceptionCodes
     {
      [ExceptionCode(1000)]
      InternalError,
     }
    
     public static (int code, string message) Translate(ExceptionCodes code)
            {
                return code.GetType()
                .GetField(Enum.GetName(typeof(ExceptionCodes), code))
                .GetCustomAttributes(false).Where((attr) =>
                {
                    return (attr is ExceptionCodeAttribute);
                }).Select(customAttr =>
                {
                    var attr = (customAttr as ExceptionCodeAttribute);
                    return (attr.Code, attr.FriendlyMessage);
                }).FirstOrDefault();
            }
    

    // Using

     var _message = Translate(code);
    

提交回复
热议问题