如何验证C#code?code

2023-09-06 16:40:50 作者:抱抱我

我工作的一个WPF应用程序,验证C#code从文件中。

I'm working on a WPF application that validates C# code from files.

我能得到的文件,针对不同的需要,实例化的类型。

I was able to get the file and, for a different need, instantiate its type.

现在我需要的是验证code对一些标准,我设置。 这是什么意思?

Now what I need is validate that code against some criteria I set. What do I mean?

让我们说我有一个文件test.cs中此文件具有以下code:

Let's say I have a file "Test.cs" and this file has the following code:

using xpto;
using abcd;

public class Test
{
    public static void Testing()
    {
        Iqueryable<XYZ> var1 = ctx.Where(c => c.IdSomething == number);
        var1 = var1.Where(v => v.Count(x => x.ValZ) > 0);
    }
}

在我的应用我会实例化这个文件(已经在做了),然后对其进行验证对一些规则。例如,在这一行:

In my app I would instantiate this file (already being done) and then validate it against some rules. For instance, in this line:

var1 = var1.Where(v => v.Count(x => x.ValZ) > 0);

我想告诉该文件使用计数(...)&GT; 0 ,而不是的任何()。我知道,可以通过文本读取文件来实现,但我想知道,如果可能的话使用反射,或者说不会要求这样的硬编码任何其他方式。 这是我做的实例文件(这是一个工作示例):

I want to tell that the file is using Count(...) > 0 instead of Any(). I know that can be done by text reading the file, but I wanted to know if that's possible using reflection, or any other way that would not require such hard coding. This is what I do to instantiate the file (this is a working example):

CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile.FullName);
Type instanceType = cr.CompiledAssembly.GetExportedTypes()
    .FirstOrDefault(e => e.Name.Equals(className));

如果这是不明确,请让我知道这样我就可以尽量详细。

If this is not clear, please let me know so I can try to elaborate.

推荐答案

好吧,就算问题往往过于笼统,你可以用的 Microsofft罗斯林。在编译器作为服务的,你可以使用 要获得 AST 从所提供的code和接受她所有你需要的nececssary信息。

Well, even if question tends to be too general, you can do it with Microsofft Roslyn. The compiler as a service which you can use to get AST from the code provided and recieve all nececssary information you need.

由于这是大的东西,它几乎可以在这里psented一些短期和自我解释的答案$ P $。它更容易对看的具体的的例子在这里如何运行的东西,例如:

As this is big stuff, it's hardly can be presented here with some short and self explanatory answer. It's easier to have a look on concrete example for "how to run stuff", for example here:

罗斯林CTP:三介绍项目