我有2個文件MyBaseClass.cs和MyScript.cs都與命名空間MainProject主DLL Main.dll:C#反思:在外部DLL類派生
public class MyBaseClass
{
public string name ;
public MyBaseClass()
{
name = "base class" ;
}
}
接下來我做了第二DLL插件.dll文件(使用MainProject)的命名空間子項目
public class MySubClass : MyBaseClass
{
public MySubClass()
{
name = "sub class" ;
}
}
我想要做的就是在加載的MyScript第二DLL,然後實例化MySubClass並投它作爲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
}
}
}
什麼
}
所以我成功的實例我MySubClass,但沒有保留遺產與MyBaseClass(或只是我投這是不對的......不知道)這是沒有用的。
他的任何人都有正確的方法來做到這一點?
在您使用類'Shoot.Ship'的'init'方法中,您已經顯示了'MyBaseClass'和'MySubClass'的定義。任何關係? – 2010-03-05 10:33:32
這只是一個錯過,當我複製我的真實項目代碼到這個樣本;) – Mickael 2010-03-05 10:47:35