我想将C#函数存储在DLL文件中,稍后使用参数调用该函数。到目前为止,我已经能够给函数存储在一个DLL文件用下面的代码:将函数存储在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;
}
}
我已经使用Assembly.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.XamlParseException未处理 Message ='匹配指定绑定约束的类型'GenericCoder.MainWindow'上构造函数的调用抛出异常。'行号“3”和行位置“9”。
有没有一种方法可以解决这个问题,或者是一种完整的新方法?
为什么在创建简单的类库时使用反射,然后从其他项目中引用输出的DLL?你是用Visual Studio开发的吗? –
不,我不能,DLL在运行时创建,并在运行时使用,而不是在项目设计 –
您是否试图实施Addin功能? –