Christofer Ohlsson
Christofer Ohlsson

Reputation: 3145

How to retrieve all fields with particular attribute?

I have a form translator that loops through a page's control collection and translates any text which has a new phrase for the current culture stored in the database. But it turns out this is not enough. I also need to be able to translate strings stored in fields. For this purpose, I want to annotate these strings with a new custom attribute called Localizable:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyProject.Business.BusinessHelp
{
    public class Localizable : Attribute
    {

    }
}

Which can be used like this:

[Localizable]
public string articles = "articles";
[Localizable]
public string summary = "summary";

(amidst many fields which aren't Localizable, of course)

So how do I retrieve a list of these at runtime, using Page or Page.Form?

Upvotes: 2

Views: 118

Answers (2)

Vojtěch Dohnal
Vojtěch Dohnal

Reputation: 8104

You are using fields, so it would be like this:

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

So the fields enumeration contains only collection of FieldInfo that have your Localizable attribute. If you would use properties, you will need to use GetProperties() instead of GetFields().

Then as soon as you want to modify fields with Localizable attribute you can do something like this:

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

Upvotes: 1

kevin
kevin

Reputation: 2213

You cannot get all the fields by looking up the attribute. You can, however, loop through all the fields and check if each one has the attribute.

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
        ....
    }
}

Upvotes: 1

Related Questions