资源文件中的C#属性文本?

Pat*_*ick 29 c# resources attributes

我有一个属性,我想从资源文件加载文本到属性.

[IntegerValidation(1, 70, ErrorMessage = Data.Messages.Speed)]
private int i_Speed;
Run Code Online (Sandbox Code Playgroud)

但我不断得到"属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式"

如果我添加一个字符串而不是Data.Messages.Text,它可以很好地工作,如:

[IntegerValidation(1, 70, ErrorMessage = "Invalid max speed")]
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Pet*_*bek 28

这是我的解决方案.我已经将resourceName和resourceType属性添加到属性,就像微软在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; 
    }
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 25

编译时,属性值被硬编码到程序集中.如果要在执行时执行任何操作,则需要使用常量作为,然后将一些代码放入属性类本身以加载资源.


Pet*_*ter 9

这是我放在一起的修改版本:

[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);
        }
    }
Run Code Online (Sandbox Code Playgroud)