无法通过反射C#接收其他dll中dll的结构数组
本文关键字:dll 其他 数组 结构 反射 | 更新日期: 2023-09-27 18:27:21
我试图通过反射调用另一个dll中的一个函数,该函数返回一个结构数组。但在运行时出现此错误"无法将first_dll.class1.mysturct[,]转换为second_dll.cclass1.mysturt[,]"
第一个dll:
/************ Ist dll ****************/
namespace first_dll
{
class class1
{
public struct mystruct
{
int a;
byte b;
};
public static mystruct[,] function1(mystruct[,] parameter)
{
//manupluating structure array here and returning it
return parameter;
}
}
}
第二个dll:
/******** Second dll *********/
namespace second_dll
{
class class1
{
Methodinfo m; // global variable
public struct mystruct
{
int a;
byte b;
};
public static void load_dll()
{
Assembly assembly = Assembly.Load(@"path of first_dll");
Type type = assembly.Gettype("first_dll.class1");
m = type.Getmethod("function1");
}
public void function2()
{
mystruct[,] structure = new mystruct[10,10];
//adding value to structure here
mystruct[,] structure_returning; // declaring structure to store retuning array;
//error occur here
structure_returning = m.Invoke(null,new object[] { structure } )
}
}
}
仅仅因为两种类型是以相同的方式声明的,所以它们并不相同。顺便说一句,这被称为duck类型,并且在C#中仅以有限的方式支持它。
为了解决这个问题,您需要第三个程序集(即类库形式的第三个项目)来定义契约。合同包含其他两个程序集中常用的类型的定义。您可以声明接口、类(可能是抽象基类)、结构等等
然后在另外两个程序集中引用此协定程序集,并使用在其中声明的类型。
例如,string
类型由以下内部名称(所谓的合格名称)标识:
System.String,mscorlib,版本=4.0.0.0,区域性=中性,PublicKeyToken=b77a5c561934e089
正如您所看到的,程序集名称"mscorlib"也包含在内。