开发者

System.Refelection.Assembly.CreateInstance broken in .NET 4.0

We upgraded from .NET 3.5 to .NET 4.0 and now System.Refelection.Assembly.CreateInstance does not appear to be working. Has anyone else had this problem? Is there a way to fix it? Below is an example of how we are loading the asembly. It returns a null value. No exception. It's a .NET Assembly registered in the GAC. It is not a COM object.

Assembly assembly = Assembly.LoadWithPartialName("AssemblyName");
object instance = assembly.CreateInstance("Namespace.Class",
                        false,
                        BindingFlags.CreateInstance,
                        null,
                        null, null, null);

I narrowed down the cause of the problem. My class A that I am trying to create inherits from class B. Class B is defined as public abstract class B. Class B contains most of the logic with one abstract method that class A defines. Similarly I have another class C that inherits from Class B that has a different开发者_高级运维 definition for the method. Basically refactoring to share common logic. This worked in .NET 3.5 but in .NET 4.0 I finally narrowed down the exception to be "{"Cannot create an abstract class."}".

public abstract class A
{
  public string InvokeUI() 
  {
    //some logic
    DisplayUI();
  }

  protected abstract void DisplayUI();
}

public class B : A
{
  protected override DisplayUI()
  {
    Some logic;
  }
}


With the Activator it works fine with .net Framework 4.0 compiled with the following platforms (x86/x64/Any CPU):

using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var ass = Assembly.Load("ConsoleApplication1");
            var type = ass.GetType("ConsoleApplication1.Test");
            var obj = Activator.CreateInstance(type);
            Console.ReadLine();


        }
    }

    public class Test    {        }
}


You have to use fusion.dll library to read the GAC. Once you find the “Full Assembly Name” you can use Reflection.[Assembly].Load() instead of Reflection.[Assembly].LoadWithPartialName(). There is the article I wrote that explains what needs to be done:

http://www.codeproject.com/Articles/485145/Late-Binding-to-NET-objects-in-NET-4-0

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜