Question

I would like to define a dynamic class like it follows:

dynamic LocalizationHelper;

string s = LocalizationHelper.View1_Question;

it should accomplish the following task:

string s = Resource.ResourceManager.GetString("View1_Question", CultureInfo.GetCultureInfoByIetfLanguageTag(Config.Language)

Is it possible so achieve something similar?

ps: i cannot do simply Resource.View1_Question because I've set the resources not to produce the c# code for doing that. And also I'm interested in the general solution. Not only for localization.

Was it helpful?

Solution

Overide DynamicObject and implement TryGetMember.

Usage

var s = LocalizationHelper.Instance.View1_Question; 
Console.WriteLine(s);

DynamicObject

class LocalizationHelper:DynamicObject
{
     static private dynamic inst = null;
     public static dynamic Instance {
        get {
            return inst ?? (inst = new LocalizationHelper());
        }
     }

     public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        string name = binder.Name.ToLower();

        result = Resource.ResourceManager.GetString(name);
        return true;
    }
}

OTHER TIPS

Yes you can. Inherit your LocalizationHelper class from DynamicObject and override the TryGetMember method.

The TryGetMember method looks like this:

public virtual bool TryGetMember(GetMemberBinder binder, out Object result)

The binder.Name will tell you what property by name did the caller ask for, so you can then look up that key in your localization dictionary and return the value by setting the out Object result.

A dynamic static field or property doesn't seem to be possible.

You can use a static property, but you will have to write out all properties that you would like.

public static class LocalizationHelper {
    public static string View1_Question {
        get { return Resource.ResourceManager.GetString("View1_Question", CultureInfo.GetCultureInfoByIetfLanguageTag(Config.Language)); }
    }
}

var q1 = LocalizationHelper.View1_Question;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top