c# - 使用 CodeDom 从外部类调用方法

标签 c# class methods codedom

我有两种方法;其中一个位于类(class)之外,另一个位于类(class)内。我希望能够使用 CodeDom 从类外部的方法调用类内部的方法。这将通过使用代码更容易解​​释...

类中有方法:

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

** 来自另一个类(class):

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

我想使用 CodeDom 重新创建上面的内容 -

CodeMemberMethod method = new CodeMemberMethod();

method.Statements.Add(new CodePropertyReferenceExpression(
new CodeVariableExpression("Public"), "ReadAllData"));

以上代码将产生以下输出 - 但请注意我无法传递任何参数!

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());

这段代码产生结果

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

另一种选择是

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

以这种方式使用 CodeMethodReferenceExpression 在调用泛型方法时可能很有用:您可以在其构造函数中指定类型参数。

关于c# - 使用 CodeDom 从外部类调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6669408/

相关文章:

java - 在 Java 中反射(reflect)方法的 Action

java - 显示 String [] args 中的值

c# - 无法读取 local.settings.json 中定义的连接字符串

c# - 将枚举转换为另一种类型的枚举

c# - 从 Collection 到 List<T> 的最快转换

c# - 获取对 View 中单击项的引用

class - 向 Scala 案例类添加一个字段?

java - Java 类和包的设计

java - 如果无法解析 import 语句会怎样?

objective-c - iPhone SDK Objective C 是否支持函数内的函数?