简体   繁体   中英

Is there any way to convert C# string classes (text files) to equivalent C# class types in .NET Core ? (Roslyn,CodeDom,… !)

I have many text files that they have poco classes. like

public class Person
{
    public long Id {get;set;}
    public string Name {get;set;}
    public int Age {get;set;}
}

In .NET Framework for convert them I had two choices :

  1. CodeDom
  2. Roslyn

CodeDom way :

    public CompilerResults ExecuteCSharpSource(string[] sources, out CompilerErrorCollection errors)
    {
        var provider = CodeDomProvider.CreateProvider("C#");
        var cp = new CompilerParameters
        {
            IncludeDebugInformation = IncludeDebugInformation,
            GenerateExecutable = GenerateExecutable,
            CompilerOptions = CompilerOptions
        };

        foreach (var ra in ReferencedAssemblies)
            cp.ReferencedAssemblies?.Add(ra);

        var results = provider.CompileAssemblyFromSource(cp, sources);
        errors = results.Errors;
        return results;
    }

Roslyn way :

public class CSharpScriptEngine
{
    static ScriptState<object> _scriptState;
    public static object Execute(string code)
    {
        _scriptState = _scriptState == null ? CSharpScript.RunAsync(code).Result : _scriptState.ContinueWithAsync(code).Result;
        return !string.IsNullOrEmpty(_scriptState.ReturnValue?.ToString()) ? _scriptState.ReturnValue : null;
    }
}

both of them seems does not exist in .NET Core.

Can anyone show me a way for do that on .NET Core ?

  • I can not use "imports": "portable-net45+win8+wp8+wpa81" for MEF 2 I need my library cross platform

Use the core Roslyn Compilation API, without ScriptEngine. Create a SyntaxTree, put it in a Compilation, then emit an assembly in memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM