How to validate C# code?

若如初见. 提交于 2020-01-05 07:26:07

问题


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.

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

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

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.


回答1:


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

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:

Roslyn CTP: Three Introductory Projects



来源:https://stackoverflow.com/questions/13729757/how-to-validate-c-sharp-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!