如何根据VS2013的委托定义生成C#委托,方法等?
问题描述:
我有一个interop类,添加功能非常麻烦,因为它涉及很多行。比方说,我需要有方法,通过ID我得让你的ID如下:如何根据VS2013的委托定义生成C#委托,方法等?
public class MyInterop
{
public class WCFDTypes
{
//....
public delegate int GetInt_Delegate(int id);
//...
}
public class DTypes
{
//....
public delegate int DotNetInterface_GetInt_Delegate(int id);
//...
}
public WCFDTypes.GetInt_Delegate GetInt;
//...
private DTypes.DotNetInterface_GetPlotLabel_Delegate Nat_GetInt;
//...
public MyInterop(string moduleName)
{
DelegateBuilder builder = new DelegateBuilder(moduleName);
//...
Nat_GetInt = Build<DTypes.DotNetInterface_GetInt_Delegate>(builder);
//..
}
//...
GetInt = (int id) =>
{
return NatGetInt(id);
}
public MyInterop(string moduleName)
{
//...
Nat_GetInt = Build<DTypes.DotNetInterface_GetInt_Delegate>(builder);
//..
}
public MyInterop(MyApplication, string address)
{
//...
GetInt = client.GetInt;
//..
}
}
解释这已经超出了这个问题的范围。我只想知道如何生成一些东西,即使没有返回类型或参数只是非变量部分(当然基于像GetInt这样的函数名)来纠正位置(包括内部类,2个方法声明和2个构造函数)。
我正在查看片段,但我发现的例子非常基本。
答
您可以使用System.Reflection中的类从程序集中读取委托定义。
Assembly asm = Assembly.LoadFrom(assemblyFile); // path to file
Type[] types = asm.GetTypes();
Here,建议您可以识别委托类型与像的方法:
public bool IsDelegate(Type type)
{
return type.IsSubClassOf(typeof(Delegate)) || type==typeof(Delegate);
}
或者用gettype(串)加载一个类型的名称,你知道的。
而且here微软笔记(重点煤矿):
公共语言运行时提供了每个委托类型的Invoke方法,用相同的签名委托。您不必从C#,Visual Basic或Visual C++显式调用此方法,因为编译器会自动调用它。 当您想要查找委托类型的签名时,Invoke方法在反射中很有用。
所以使用这样获得的MethodInfo,告诉你委托的帕拉姆和返回类型:
MethodInfo methodInfo = delegateType.GetMethod("Invoke");
了解这些我希望你现在就可以生成你所需要的。可以在运行时生成一个方法。请参阅here或搜索“发出动态方法和组件”。
但是你可以代替编写源代码(如您的片段),以供以后编辑文件,如果你愿意,你可以用自动化的System.CodeDom.Compiler汇编,例如:
CodeDomProvider provider = CodeDomProvider.CreateProvider("CS"); // source language
CompilerParameters compParams = new CompilerParameters();
compParams.IncludeDebugInformation = true;
foreach (string refAsm in referencedAssemblies) {
compParams.ReferencedAssemblies.Add(refAsm);
}
// etc
CompilerResults res = provider.CompileAssemblyFromSource(compParams, codeSource);
if (res.Errors.Count > 0) {
// display & throw
}
注codeSource
这里不是源文件的路径,而是包含实际源代码的一个或多个字符串。因此,您甚至可以生成并编译源代码,而无需将其写入文件的中间步骤。
这当然是最糟糕的做法。为什么不能使用[DllImport]或C++/CLI包装程序完全不清楚。 –
这不是我的代码。正如我所说,这超出了这个问题的范围。 –
加上它使用本机dll的DllImport。也适用于WCF的外部插件。 –