【问题标题】:How to retrieve all fields with particular attribute?如何检索具有特定属性的所有字段?
【发布时间】:2014-08-25 09:05:18
【问题描述】:

我有一个表单翻译器,它遍历页面的控件集合并翻译任何文本,其中包含存储在数据库中的当前文化的新短语。但事实证明这还不够。我还需要能够翻译存储在字段中的字符串。为此,我想用一个名为 Localizable 的新自定义属性来注释这些字符串:

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 检索这些列表?

【问题讨论】:

标签: c# asp.net


【解决方案1】:

你正在使用字段,所以它会是这样的:

 using System.Reflection;
 Type outputType = Type.GetType("MyNamespace.MyClass, MyAssembly");
 IEnumerable<FieldInfo> fields = outputType.GetFields().Where(
       p => p.GetCustomAttribute(typeof(Localizable)) != null);

所以fields 枚举仅包含具有Localizable 属性的FieldInfo 集合。如果要使用属性,则需要使用GetProperties() 而不是GetFields()

然后,只要您想修改具有Localizable 属性的字段,您就可以执行以下操作:

MyClass mc = new MyClass();
fields.First(x=>x.Name == "articles").SetValue(mc, "Das ist ein Artikel.");

【讨论】:

【解决方案2】:

您无法通过查找属性来获取所有字段。但是,您可以遍历所有字段并检查每个字段是否具有该属性。

foreach(FieldInfo f in typeof(SomeClass).GetFields()){
    if (f.GetCustomAttributes().Any(t=>t is LocalizableAttribute)) {
        var name = f.Name; //this is how you get the field name
        ....
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 2014-05-03
    • 2012-05-19
    • 2010-10-17
    • 1970-01-01
    相关资源
    最近更新 更多