获取自定义资源和自定义键,将字符串转换为"ResourceManager"



我正在尝试在ASP.NET中获取用于翻译的资源,使用字符串转换为ResourceManager类型和用于翻译的外部资源文件。但当我执行时,我会看到这个错误:

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

这是我的代码:

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();
}

显然,getString变量返回null,但是te方法";GetString"应调用";GetString"方法。有人能帮我吗?

MethodInfo.Invoke的第一个参数必须是某个对象的实例(据我所知,它需要与您所反思的类型相同,在您的案例中是Website.Language.{translation}.general(。

这可能不起作用,但只是向你展示你需要朝哪个方向前进。

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();
}

另请参见此示例。

最新更新