C# 获取自定义资源和自定义密钥,将字符串转换为;资源经理“;

C# 获取自定义资源和自定义密钥,将字符串转换为;资源经理“;,c#,asp.net,reflection,resx,C#,Asp.net,Reflection,Resx,我正在尝试在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 stac

我正在尝试在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,但是方法“getString”应该是ResourceManager的调用“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();
}

另请参见示例。

您试图在实例
this
上调用方法
GetString
,但是
MethodInfo
来自type
MSD_Website.Language.{translation}.general
。您好@Michael,我将此更改为元素,在更改为myProp之后,我得到了相同的错误