C# attribute text from resource file?

前端 未结 9 1227
难免孤独
难免孤独 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:28

    Here is the modified version of the one I put together:

    [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = false)]
    public class ProviderIconAttribute : Attribute
    {
        public Image ProviderIcon { get; protected set; }
    
        public ProviderIconAttribute(Type resourceType, string resourceName)
        {
            var value = ResourceHelper.GetResourceLookup<Image>(resourceType, resourceName);
    
            this.ProviderIcon = value;
        }
    }
    
        //From http://stackoverflow.com/questions/1150874/c-sharp-attribute-text-from-resource-file
        //Only thing I changed was adding NonPublic to binding flags since our images come from other dll's
        // and making it generic, as the original only supports strings
        public class ResourceHelper
        {
            public static T GetResourceLookup<T>(Type resourceType, string resourceName)
            {
                if ((resourceType != null) && (resourceName != null))
                {
                    PropertyInfo property = resourceType.GetProperty(resourceName, BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);
                    if (property == null)
                    {
                        return default(T);
                    }
    
                    return (T)property.GetValue(null, null);
                }
                return default(T);
            }
        }
    
    0 讨论(0)
  • 2020-12-14 07:36

    Attribute values are hard-coded into the assembly when you compile. If you want to do anything at execution time, you'll need to use a constant as the key, then put some code into the attribute class itself to load the resource.

    0 讨论(0)
  • 2020-12-14 07:39

    If you're using .NET 3.5 or newer you can use ErrorMessageResourceName and ErrorMessageResourceType parameters.

    For example [Required(ErrorMessageResourceName ="attribute_name" , ErrorMessageResourceType = typeof(resource_file_type))]

    0 讨论(0)
提交回复
热议问题