【问题标题】:How to manipulate c# code programatically In .Net Core?如何在 .Net Core 中以编程方式操作 c# 代码?
【发布时间】:2019-09-26 21:07:26
【问题描述】:

在 .Net Core 中,我想操作 .cs 文件。例如我想添加/删除/更改方法。 有没有图书馆可以做到这一点?

示例 我有 Plugins.cs 文件如下:

public class Plugins
{

    public static JToken GetPluginsList(JObject inputs, ControllerBase controlerBase)
    {
        // all plugins in repo
        return true;
    }

    public static JToken GetInstalledPluginsList(JObject inputs, ControllerBase controlerBase)
    {
        return true;
    }

    public static JToken InstallPlugin(JObject inputs, ControllerBase controlerBase)
    {
        return true;
    }

    public static JToken UnInstallPlugin(JObject inputs, ControllerBase controlerBase)
    {
        return true;
    }

    public static JToken RemovePluginFromRepo(JObject inputs, ControllerBase controlerBase)
    {
        // some implementation
        return true;
    }

}

我需要一些 API 来操作上面的代码。例如,我想添加新方法或获取现有方法的主体。

这样的:

somelib.GetMethodBody("RemovePluginFromRepo").Body

返回:

// some implementation
return true;

【问题讨论】:

  • 到目前为止你尝试过什么?什么有效,什么无效?请提供a Minimal, Complete, and Verifiable example
  • 我认为任何对代码的语法操作都会是一场灾难,也许你的意思是programmatically

标签: c# code-generation


【解决方案1】:

C# 不是脚本语言。它需要在执行前编译。因此,虽然您可以“以编程方式”修改 .cs 文件或任何其他类型文件的内容,但它不会对可执行文件的运行/工作方式产生影响。完成您所要求的唯一方法 - 即“添加/删除/更改方法” - 将使用称为委托的东西。您仍然需要创建程序可能需要的几乎所有可能的方法,但是委托可以让您可以将方法作为参数传递,从而有效地完成您的要求。

【讨论】:

  • 感谢您的回复。我正在使用脚本引擎在运行时运行主题。所以问题是代码操作。
【解决方案2】:

您可以查看 System.CodeDom 命名空间中的功能。

https://docs.microsoft.com/en-us/dotnet/api/system.codedom

这可能不是您所期望的,但也许它为您提供了一些有用的东西。

【讨论】:

    【解决方案3】:

    有一个简单的方法:

    using Microsoft.CodeAnalysis;
    using Microsoft.CodeAnalysis.CSharp;
    using Microsoft.CodeAnalysis.CSharp.Syntax;
    
    
    SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceCode);
    
    MethodDeclarationSyntax method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>()
        .First(m => m.Identifier.ToString() == "methodName");
    
    method.Body.ToFullString();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多