在DLL文件中存储函数

时间:2016-10-04 11:34:30

标签: c# function dll

我想在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;
    }
}

我使用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 =&#39;在类型&#39; GenericCoder.MainWindow&#39;上调用构造函数。匹配指定的绑定约束引发异常。&#39;行号&#39; 3&#39;和行位置&#39; 9&#39;。

有没有办法解决这个问题,或者可能采取一种全新的方法来解决这个问题?

1 个答案:

答案 0 :(得分:0)

将您的库添加到项目的引用中。然后你就可以在不需要反射的情况下使用这些功能了。