我正在尝试向我的程序中添加插件,这看起来不错,只是我无法从dll中转换正确的类型。
我有一个解决方案,上面有几个项目。
接口(公共接口IContryBase)
在另一个项目中,我为国家“实施”。此dll在运行时加载,使用以下方法:
Assembly assembly = Assembly.LoadFrom(file);
//get the class from the assembly
foreach (Type t in assembly.GetTypes())
{
//just for debugging
Console.WriteLine(t.FullName);
}
Type localType = assembly.GetType( "CountryLayers.Local");
if (localType != null)
{
Country countrydata = new Country();
countrydata.ObjectType = localType;
countrydata.CountryObject = Activator.CreateInstance(localType);
countrydata.CountryObject2 = (CountryBase) countrydata.CountryObject;
countrydata.FileName = file;
CountryList.Add(countrydata);
}
其中Local是定义为公共类Local的类的名称:CountryLayers.CountryBase、CountryLayers.icontrybase
countrydata只保存指针。CountryObject2被定义为CountryBase(我也尝试过作为IcountryBase)。但它总是返回类型不可转换。
控制台writeline显示程序集中加载了属于countrylayer的所有类以及本地类。
所以在这一点上,我不知道错误是因为我所有的东西都在同一个解决方案上,还是因为我使用接口和抽象类的顺序不好。同样,当create instance返回对象时,该对象具有抽象类中定义的所有属性,但没有方法。