初学者的反思问题

tnw*_*tnw 2 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) { }
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

问题是你从来没有给一个值赋值asm,所以它的默认值是null.也许你打算用assemblyInstance呢?

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

object lateBoundObj = Activator.CreateInstance(t);
Run Code Online (Sandbox Code Playgroud)

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

catch (Exception ex) { }
Run Code Online (Sandbox Code Playgroud)

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