简体   繁体   中英

C# - create a class based on a list of string

I need to create a class in runtime with properties based on a list of strings. I then need to populate this new class with values before I serialize it. Have looked at dynamics in C# and also anonymous types but can't get it to work. Any help appreciated. Thanks!

//1. List of string with the properties I need
List<string> properties = new List<string>();
properties.Add("Id");
properties.Add("Name");
//2. Create class called className with properties above 
//todo
//3. Populate with values
//todo
//4. Serialize to JSON
JavaScriptSerializer jScriptSerializer = new JavaScriptSerializer();
string jsonString = jScriptSerializer.Serialize(className);

The task of turning text into classes traditionally belongs to two parts of the system: compilation and serialisation. That makes for several methods I can think of.

  1. Compilation using Reflection.Emit. The class to start with is TypeBuilder, but you'll need several more.
  2. Compilation using Roslyn. Roslyn exposes an API for dynamic compilation.
  3. Compilation using the C# compiler. Create a valid program as a string and compile it. Pull the type you need out of the assembly using System.Type.
  4. Deserialisation via JSON. Create a valid JSON object as a string and deserialise it.
  5. Deserialisation via XML. Create a valid XML schema as a string and deserialise it.

I would use Reflection.Emit because I'm familiar with it, but they are all more or less feasible.

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