开发者

Call method from an outside class using CodeDom

I have two methods; one of which resides outside of a class, the other inside a class. I would like to be able to use CodeDom to make a call from the method outside of the class, to the one inside of the class. This will be much easier to explain through the use of code...

Class with method inside:

public static class Public
{
    public static byte[] ReadAllData(string sFilePath)
    {
        byte[] b = new byte[sFilePath.Length];
        b = System.IO.File.ReadAllBytes(sFilePath);
        return b;
    }  
}

** from another class:

Public.ReadAllData(@"C:\File.exe");

I want to recreate the above using CodeDom -

CodeMemberMethod method = new CodeMemberMethod();

method.Statements.Add(new CodePropertyReferenceExpression(
new CodeVariableExpression("Publi开发者_开发知识库c"), "ReadAllData"));

The above code will produce the following output - but notice I was not able to pass any parameters!

Public.ReadAllData;


var compiler = new CSharpCodeProvider();

var invocation = new CodeMethodInvokeExpression(
    new CodeTypeReferenceExpression(typeof(Public)),
    "ReadAllData", new CodePrimitiveExpression(@"C:\File.exe"));

var stringWriter = new StringWriter();
compiler.GenerateCodeFromExpression(invocation, stringWriter, null);
Console.WriteLine(stringWriter.ToString());

This code produces the result

ConsoleApplication1.Public.ReadAllData("C:\\File.exe")

Another option is

var invocation = new CodeMethodInvokeExpression(
    new CodeMethodReferenceExpression(
        new CodeTypeReferenceExpression(typeof(Public)),"ReadAllData"),
    new CodePrimitiveExpression(@"C:\File.exe"));

Using CodeMethodReferenceExpression this way could be useful when calling generic methods: you can specify type parameters in its constructor.


I've only used CodeDom a bit, but I think you'll want the CodeMethodInvokeExpression, instead of CodePropertyReferenceExpression. It looks like CodePropertyReferenceExpression is generating a statement that is accessing a property value, rather than invoking a method.

There is a Parameters property on CodeMethodInvokeExpression that will allow you to specify the parameters to pass to the method you are wanting to invoke.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜