我有一个表单翻译器,它循环访问页面的控件集合,并翻译任何具有数据库中存储的当前区域性新短语的文本。但事实证明这还不够。我还需要能够翻译存储在字段中的字符串。为此,我想使用名为 Localized 的新自定义属性来注释这些字符串:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyProject.Business.BusinessHelp
{
public class Localizable : Attribute
{
}
}
可以这样使用:
[Localizable]
public string articles = "articles";
[Localizable]
public string summary = "summary";
(当然,在许多不可本地化的字段中)
那么如何使用 Page 或 Page.Form 在运行时检索这些列表?
最佳答案
您正在使用字段,因此它会是这样的:
using System.Reflection;
Type outputType = Type.GetType("MyNamespace.MyClass, MyAssembly");
IEnumerable<FieldInfo> fields = outputType.GetFields().Where(
p => p.GetCustomAttribute(typeof(Localizable)) != null);
因此,fields
枚举仅包含具有 Localized
属性的 FieldInfo
集合。如果您要使用属性,则需要使用 GetProperties()
而不是 GetFields()
。
然后,一旦您想要修改具有 Localized
属性的字段,您就可以执行以下操作:
MyClass mc = new MyClass();
fields.First(x=>x.Name == "articles").SetValue(mc, "Das ist ein Artikel.");
关于c# - 如何检索具有特定属性的所有字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25482401/