我正在尝试学习 C# 中的反射,需要一些有关我的代码的帮助。我很难找到好的代码示例/指南,所以如果我的代码做得不好,我深表歉意。
本质上,我只是尝试检查给定程序集 dll 中的特定方法名称(路径和方法名称已被编辑)。
问题出现在 object lateBoundObj = asm.CreateInstance(typeName);
行上,它显示为 An object reference is required for the non-static field, method, or property.. .
我知道这与静态与非静态以及创建 new Assembly
或类似的东西有关,但需要一些帮助来理解问题以及如何解决它。
谢谢!
public const string assemblyPath = @"<my file path>";
Assembly asm;
static void Main(string[] args)
{
//asm = new Assembly();
Console.Read();
MethodInfo mi;
object result = null;
object[] arguments = new object[] { "ABC123" };
try
{
Assembly assemblyInstance = Assembly.LoadFrom(assemblyPath);
Type[] types = assemblyInstance.GetTypes();
foreach (Type t in types)
{
mi = t.GetMethod("<my method name>");
if (mi != null)
{
string typeName = t.FullName;
object lateBoundObj = asm.CreateInstance(typeName);
result = t.InvokeMember("GetWeb", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, null, lateBoundObj, arguments);
break;
}
}
//set return for find method
}
catch (Exception ex) { }
}
最佳答案
问题是您永远不会为 asm
赋值,因此它的默认值为 null
。也许您打算改用 assemblyInstance
?
事实上,我根本不会在那里使用 Assembly.CreateInstance
或 Type.FullName
- 我会使用:
object lateBoundObj = Activator.CreateInstance(t);
另请注意,您应该始终避免这样的代码:
catch (Exception ex) { }
总是至少记录异常。理想情况下,不要捕获您根本无法真正“处理”的异常。
关于c# - 初学者的反射(reflection)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12390709/