C# attribute text from resource file?

前端 未结 9 1269
难免孤独
难免孤独 2020-12-14 06:53

I have an attribute and i want to load text to the attribute from a resource file.

[IntegerValidation(1, 70, ErrorMessage = Data.Messages.Speed)]
private int         


        
9条回答
  •  难免孤独
    2020-12-14 07:27

    Here is my solution. I've added resourceName and resourceType properties to attribute, like microsoft has done in DataAnnotations.

    public class CustomAttribute : Attribute
    {
    
        public CustomAttribute(Type resourceType, string resourceName)
        {
                Message = ResourceHelper.GetResourceLookup(resourceType, resourceName);
        }
    
        public string Message { get; set; }
    }
    
    public class ResourceHelper
    {
        public static  string GetResourceLookup(Type resourceType, string resourceName)
        {
            if ((resourceType != null) && (resourceName != null))
            {
                PropertyInfo property = resourceType.GetProperty(resourceName, BindingFlags.Public | BindingFlags.Static);
                if (property == null)
                {
                    throw new InvalidOperationException(string.Format("Resource Type Does Not Have Property"));
                }
                if (property.PropertyType != typeof(string))
                {
                    throw new InvalidOperationException(string.Format("Resource Property is Not String Type"));
                }
                return (string)property.GetValue(null, null);
            }
            return null; 
        }
    }
    

提交回复
热议问题