在DLL文件中存储功能
本文关键字:存储 功能 文件 DLL | 更新日期: 2023-09-27 18:11:30
我想在DLL文件中存储c#函数,然后用参数调用该函数。到目前为止,我已经能够用以下代码将函数存储在DLL文件中:
var codeProvider = new CSharpCodeProvider();
var icc = codeProvider.CreateCompiler();
var parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.OutputAssembly = "Sum.dll";
icc.CompileAssemblyFromSource(parameters, code);
DLL文件中的函数(上面变量代码的值为):
public class Function : IFunc
{
public string ID
{
get { return ""Sum""; }
}
public string Name
{
get { return ""Sum""; }
}
public string Description
{
get { return ""Return the sum of the values specified in args""; }
}
public ResultSet Execute(params string[] args)
{
var sum = 0;
foreach(var arg in args)
{
var rslt = 0;
if(int.TryParse(arg, out rslt))
{
sum += rslt;
}
}
ResultSet rtn = new ResultSet();
rtn.Result = sum.ToString();
rtn.Type = ""int"";
return rtn;
}
}
我使用了汇编。LoadFile加载DLL,并使用反射获取包含该函数的类。我也有2个相同的接口,一个在我的项目和一个在DLL文件:
public interface IFunc
{
string ID { get; }
string Name { get; }
string Description { get; }
string Execute(params string[] args);
}
为了能够调用函数,我使用:
public static IFunc CreateSumFunction()
{
var dll = Assembly.LoadFile(@"...'Sum.dll");
var func = dll.GetType("Function"); // Class containing the function
var instance = Activator.CreateInstance(func);
return (IFunc)instance; // <--- CRASH
}
部分例外:
System.Windows.Markup。未处理XamlParseExceptionMessage='调用类型'GenericCoder的构造函数。与指定绑定约束匹配的主窗口抛出了异常。行号'3',行位'9'。
有没有办法解决这个问题,或者可能是一种全新的方法?
将库添加到项目的引用中。这样你就可以使用这些函数而不需要反射了。