C# 如何从带有反射的静态方法调用实例类方法
这会被静态调用,并给我一个答案C# 如何从带有反射的静态方法调用实例类方法,c#,dll,.net-assembly,C#,Dll,.net Assembly,这会被静态调用,并给我一个答案 namespace ClassLibraryB { public class Class1 { public void Add(int ii, int jj) { i = ii; j = jj; result = i + j; } public void Add2() { resul
namespace ClassLibraryB {
public class Class1 {
public void Add(int ii, int jj)
{
i = ii;
j = jj;
result = i + j;
}
public void Add2()
{
result = i + j;
}
}
}
但是,当我尝试使用below调用dll时,它失败了,因为它不是静态的
ClassLibraryB.Class1 objB = new ClassLibraryB.Class1();
objB.Add(4, 16);
objB.Add2();
kk = objB.result;
textBox1.Text += "Addition =" + kk.ToString() + "\r\n";
我只需要确切地知道我必须对dll类做哪些更改才能在此处调用它您必须将该类型的实例传递给
InvokeMember
Assembly testAssembly = Assembly.LoadFile(strDLL);
Type calcType = testAssembly.GetType("ClassLibraryB.Class1");
object calcInstance = Activator.CreateInstance(calcType);
PropertyInfo numberPropertyInfo = calcType.GetProperty("i");
numberPropertyInfo.SetValue(calcInstance, 5, null);
PropertyInfo numberPropertyInfo2 = calcType.GetProperty("j");
numberPropertyInfo2.SetValue(calcInstance, 15, null);
int value2 = (int)numberPropertyInfo.GetValue(calcInstance, null);
int value3 = (int)numberPropertyInfo2.GetValue(calcInstance, null);
calcType.InvokeMember("Add2",BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
null, null, null);
PropertyInfo numberPropertyInfo3 = calcType.GetProperty("result");
int value4 = (int)numberPropertyInfo3.GetValue(calcInstance, null);
如果要创建插件,正确的做法是使用三个程序集
接口组件
Calculator.Contracts.dll
calcType.InvokeMember("Add2", flags, null, calcInstance, null);
public interface ICalculator
{
int Add(int a, int b);
}
插件实现
Calculator.dll
calcType.InvokeMember("Add2", flags, null, calcInstance, null);
public interface ICalculator
{
int Add(int a, int b);
}
现在,您可以加载插件并在应用程序(exe)中以键入方式使用它:
你为什么要用反射来加载它,而不是仅仅引用它,有什么具体的原因吗?没有。我只是想找一个例子来调用一个dll函数,传递一些参数并得到一个简单的值,这些值都是c语言的,没有
结果
声明。当调用Add2时,Bit失败。非静态方法需要一个目标。接口直接进入命名空间内自己的dll(类库)。此DLL不包含任何其他内容。你可以调用这个程序集Calculator.Contracts.dll
。这一切都很好。一些项目依赖项出现了问题,但现在已经解决了,所以非常感谢您的帮助