开发者

C# Reflection : Class Derivation in external dll

I Have a main dll Main.dll with 2 files MyBaseClass.cs and MyScript.cs both with namespace MainProject:

public class MyBaseClass
{
    public string name ;

    public MyBaseClass()
    {
        name = "base class" ;   
    }
}

Next i've made a second dll addOn.dll (using MainProject) with开发者_如何学JAVA namespace SubProject

public class MySubClass : MyBaseClass
{
    public MySubClass()
    {
        name = "sub class" ;
    }
}

What i want to do is loading the second dll in MyScript, then instanciate MySubClass and cast it as MyBaseClass

public class MyScript
{

public static void init()
    {

        string myPath = ".../addOn.dll" ;
        Assembly testAssembly = System.Reflection.Assembly.LoadFrom( myPath ) ;

        //i retrieve types in external Assembly     
        Type[] myTypes = testAssembly.GetExportedTypes() ;

        for(int i = 0; i < myTypes.Length; ++i)     
        {
           //instanciate type => there is only MySubClass   
           System.Object testObj = testAssembly.CreateInstance( myTypes[i].ToString() ) ;
           Debug.Log( testObj ) ; //=> print SubProject.MySubClass
          Debug.Log(myTypes[i].BaseType ) ; //=>print MainProject.MyBaseClass 
           Debug.Log( myTypes[i].IsSubclassOf(typeof(MainProject.MyBaseClass))) ; 
           //=> print False. => It's seems that mySubClass doesn't derive from MyBaseClass anymore ?

           //cast
           MyBaseClass testCastObj = testObj as MyBaseClass;
           Debug.Log( testCastObj ) ; //print null (cast fail)

           //test if properties are well retrieved  
           PropertyInfo[] propList = testObj.GetType().GetProperties() ;
           for(int j = 0; j < propList.Length; ++j)
           {
                Debug.Log( propList[j].Name.ToString() ) ; //print name, it's ok    
           }
        }
    }

}

So i succeed in instantiate my MySubClass, but without keeping heritage with MyBaseClass (or just my cast which is wrong... don't know) this is useless.

His anyone have the right way to do this?


Maybe addon.dll is using a local copy of main.dll.
What happens if you put the two dlls in the same folder?


Do you have different versions of your Main.dll floating around, by chance? In that case addon.dll might define a type that inherits from MyBaseClass (in Main.dll V 1.0.0.0) and you try to cast it to MyBaseClass (in Main.dll V 1.1.0.0) - which wouldn't work.

Let me add as a sidenote, that I'd recommend against rolling your own plugin framework, if possible. There are a lot of ready-made solutions or good frameworks out there that make your job easier.

  • Mono.Addins
  • Managed Extensibility Framework
  • Microsoft Enterprise Library
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜