Get custom resource and custom key converting string to “ResourceManager”

I’m trying get a resource for translation in ASP.NET, using conversion of string to type ResourceManager and a extertnal Resources file for translation. But when i execute i’m look this error:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:

Line 24:             Type myProp = element.GetProperty("ResourceManager").GetType();
Line 25:             MethodInfo getString = myProp.GetMethod("GetString");
Line 26:             var r = getString.Invoke(this, new object[] { key });
Line 27:             return r.ToString();
Line 28:         }

This is my code:
protected string getText(string key)
{
    Type element = Type.GetType($"Website.Language.{translation}.general");
    Type myProp = element.GetProperty("ResourceManager").GetType();
    MethodInfo getString = myProp.GetMethod("GetString");
    var r = getString.Invoke(this, new object[] { key });
    return r.ToString();
}

Apparently, the getString variable returns null, but te method “GetString” should be call “GetString” method of ResourceManager.
Someone could help me with this?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The first parameter of MethodInfo.Invoke must be an instance of some object (as far as I know, it needs to be of the same type that you reflect on, in your case Website.Language.{translation}.general).

This might not work, but just to show you in which direction you need to go.

protected string getText(string key)
{
    Type element = Type.GetType($"Website.Language.{translation}.general");
    var instance = Activator.CreateInstance(element);
    Type myProp = element.GetProperty("ResourceManager").GetType();
    MethodInfo getString = myProp.GetMethod("GetString");
    var r = getString.Invoke(instance, new object[] { key });
    return r.ToString();
}

See also this example.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x