初学者的反思问题

时间:2012-09-12 14:40:10

标签: c# binding visual-studio-2012

我正在尝试学习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) { }
    }

2 个答案:

答案 0 :(得分:6)

问题在于,您永远不会为asm分配值,因此它的默认值为null。也许您打算使用assemblyInstance代替?

事实上,我根本不会使用Assembly.CreateInstanceType.FullName - 我会使用:

object lateBoundObj = Activator.CreateInstance(t);

另请注意,您应该始终避免使用以下代码:

catch (Exception ex) { }

始终至少记录异常。理想情况下,不要捕捉到根本无法真正“处理”的异常。

答案 1 :(得分:2)

永远不会分配

asm变量。您应该在CreateInstance上致电assemblyInstance