我有一个属性,我想从资源文件中将文本加载到属性中。
[IntegerValidation(1, 70, ErrorMessage = Data.Messages.Speed)]
private int i_Speed;
但我一直在努力 “属性参数必须是属性参数类型”
的常量表达式,typeof表达式或数组创建表达式如果我添加一个字符串而不是Data.Messages.Text,它可以很好地工作,如:
[IntegerValidation(1, 70, ErrorMessage = "Invalid max speed")]
有什么想法吗?
答案 0 :(得分: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;
}
}
答案 1 :(得分:24)
编译时,属性值被硬编码到程序集中。如果要在执行时执行任何操作,则需要使用常量作为键,然后将一些代码放入属性类本身以加载资源。
答案 2 :(得分: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);
}
}
答案 3 :(得分:2)
我遇到了属性的显示名称这个问题,我做了以下更改:
对于我们的资源文件,我将自定义工具属性更改为<MyComponent>
<div id="first_layer">
<input id="first_input"/>
<div id="second_layer">
<input id="deepest_child"/>
<div/>
<div/>
<MyComponent/>
然后将其添加到属性:
PublicResXFileCodeGenerator
答案 4 :(得分:1)
使用字符串作为资源的名称。 .NET使用一些内部属性来做到这一点。
答案 5 :(得分:1)
属性的性质使得您在属性属性中放置的数据必须是常量。这些值将存储在程序集中,但永远不会导致执行的已编译代码。因此,您不能拥有依赖于执行的属性值来计算结果。
答案 6 :(得分:0)
这是我写的东西,因为我找不到任何其他的东西。:
<强>输入强>
在项目A中编写一个常量字符串类。
[GenerateResource]
public static class ResourceFileName
{
public static class ThisSupports
{
public static class NestedClasses
{
[Comment("Comment value")]
public const string ResourceKey = "Resource Value";
}
}
}
<强>输出强>
将在包含常量类的项目中生成资源。
您需要做的就是在某个地方使用此代码:
<强>来源
public class CommentAttribute : Attribute
{
public CommentAttribute(string comment)
{
this.Comment = comment;
}
public string Comment { get; set; }
}
public class GenerateResourceAttribute : Attribute
{
public string FileName { get; set; }
}
public class ResourceGenerator
{
public ResourceGenerator(IEnumerable<Assembly> assemblies)
{
// Loop over the provided assemblies.
foreach (var assembly in assemblies)
{
// Loop over each type in the assembly.
foreach (var type in assembly.GetTypes())
{
// See if the type has the GenerateResource attribute.
var attribute = type.GetCustomAttribute<GenerateResourceAttribute>(false);
if (attribute != null)
{
// If so determine the output directory. First assume it's the current directory.
var outputDirectory = Directory.GetCurrentDirectory();
// Is this assembly part of the output directory?
var index = outputDirectory.LastIndexOf(typeof(ResourceGenerator).Assembly.GetName().Name);
if (index >= 0)
{
// If so remove it and anything after it.
outputDirectory = outputDirectory.Substring(0, index);
// Is the concatenation of the output directory and the target assembly name not a directory?
outputDirectory = Path.Combine(outputDirectory, type.Assembly.GetName().Name);
if (!Directory.Exists(outputDirectory))
{
// If that is the case make it the current directory.
outputDirectory = Directory.GetCurrentDirectory();
}
}
// Use the default file name (Type + "Resources") if one was not provided.
var fileName = attribute.FileName;
if (fileName == null)
{
fileName = type.Name + "Resources";
}
// Add .resx to the end of the file name.
fileName = Path.Combine(outputDirectory, fileName);
if (!fileName.EndsWith(".resx", StringComparison.InvariantCultureIgnoreCase))
{
fileName += ".resx";
}
using (var resx = new ResXResourceWriter(fileName))
{
var tuples = this.GetTuplesRecursive("", type).OrderBy(t => t.Item1);
foreach (var tuple in tuples)
{
var key = tuple.Item1 + tuple.Item2.Name;
var value = tuple.Item2.GetValue(null);
string comment = null;
var commentAttribute = tuple.Item2.GetCustomAttribute<CommentAttribute>();
if (commentAttribute != null)
{
comment = commentAttribute.Comment;
}
resx.AddResource(new ResXDataNode(key, value) { Comment = comment });
}
}
}
}
}
}
private IEnumerable<Tuple<string, FieldInfo>> GetTuplesRecursive(string prefix, Type type)
{
// Get the properties for the current type.
foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.Static))
{
yield return new Tuple<string, FieldInfo>(prefix, field);
}
// Get the properties for each child type.
foreach (var nestedType in type.GetNestedTypes())
{
foreach (var tuple in this.GetTuplesRecursive(prefix + nestedType.Name, nestedType))
{
yield return tuple;
}
}
}
}
然后创建一个小项目,其中包含[GenerateResource]
public class Program
{
static void Main(string[] args)
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
string path = Directory.GetCurrentDirectory();
foreach (string dll in Directory.GetFiles(path, "*.dll"))
{
assemblies.Add(Assembly.LoadFile(dll));
}
assemblies = assemblies.Distinct().ToList();
new ResourceGenerator(assemblies);
}
}
然后您的属性可以使用静态类ResourceFileName.ThisSupports.NestedClasses.ResourceKey
,而其他代码可以使用资源文件。
您可能需要根据您的特定需求进行定制。
答案 7 :(得分:0)
我有类似的情况,我需要将资源字符串放入属性中。在C#6中,我们具有nameof()
能力,这似乎可以解决问题。
就我而言,我可以使用[SomeAttribute(nameof(Resources.SomeResourceKey))]
并且编译得很好。然后我只需要在另一端做一些工作就可以使用该值从Resources文件中获取正确的字符串。
在您的情况下,您可以尝试:
[IntegerValidation(1, 70, ErrorMessageResourceKey = nameof(Data.Messages.Speed))]
private int i_Speed;
然后你可以按照(伪代码)的方式做一些事情:
Properties.Resources.ResourceManager.GetString(attribute.ErrorMessageResourceKey);
答案 8 :(得分:0)
如果您使用的是.NET 3.5或更高版本,则可以使用ErrorMessageResourceName
和ErrorMessageResourceType
参数。
例如
[Required(ErrorMessageResourceName ="attribute_name" , ErrorMessageResourceType = typeof(resource_file_type))]