我有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