oleg-shilo / cs-script

C# scripting platform
http://www.cs-script.net
MIT License
1.56k stars 234 forks source link

cs-script+Newtonsoft.Json #377

Open snikeguo opened 1 week ago

snikeguo commented 1 week ago

my program code: step1: loading user script and SerializeObject iterInstance(ClassA) ->a.json

public interface IIter
{
    int V{get;set;}
}
...
userAssembly=CSScript.RoslynEvaluator.CompileCode(userCode, CodeKind = SourceCodeKind.Script );
iterInstance=userAssembly.Create(class A  full Name);
···

    var settings = new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.All//!!!** see  https://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm
    };

    var str=JsonConvert.SerializeObject(iterInstance,Newtonsoft.Json.Formatting.Indented, settings);//Serialize class A
    File.WriteAllText("a.json", str);
}
...

the user code:

class A:IIter
{
   int V{get;set;}
  int V2{get;set;}
}

class B:IIter
{
   int V{get;set;}
  int V2{get;set;}
}
//ClasseA and B are the same except for their type names, which means they have the same fields, the same properties, and so on.

step2: loading user script and DeserializeObject ,a.json->a(class A's object )

CSScriptLoadingUserScript(userCode);
a=JsonConvert.DeserializeObject(a.json's content);

I am unaware of the specific type of the user's a.json file, and each time CSScript generates an Assembly, its Type may change, resulting in a mismatch between the type specified in the json and the type of the Assembly.

How can we solve this problem? image

snikeguo commented 1 week ago

The problem has been solved: just specify the AssemblyName. eg: new CompileInfo { CodeKind = SourceCodeKind.Script, AssemblyName="aaa"}

oleg-shilo commented 1 week ago

Perfect. Thank you for sharing the solution