C#中的动态类创建

是否有可能在运行时从DataTable创建一个类,其中ColumnName将是动态类属性?

使用C#4,您可以执行此操作

dynamic foo = new ExpandoObject(); // mimic grabbing a column name at runtime and adding it as a property ((IDictionary)foo).Add("Name", "Apple"); Console.WriteLine(foo.Name); // writes Apple to screen 

不推荐它或任何东西,但它告诉你它是可能的。

是的(使用Reflection.Emit),但这是一个坏主意。
你想做什么?

如果你有C#4,你可以使用新的动力学特性和ExpandoObject 。 您可以在此处阅读有关它的教程 。

读你的评论,我不明白你的意思。 只需使用Generics:使用List字段生成对象。 代码很简单:

 public class DynClass { public DynClass() { _fields = new Dictionary(); } private IDictionary _fields; public IDictionary Fields { get { return _fields; } } } public class TestGenericInstances { public TestGenericInstances() { Client cli = new Client("Ash", "99999999901"); /* Here you can create any instances of the Class. * Also DynClass * */ DynClass gen = new DynClass(); /* Add the fields * */ gen.Fields.Add("clientName", cli); /* Add the objects to the List * */ List lstDyn = new List().Add(gen); } } 

我将要查看上面提到的ExpandoObject(我按顺序投票选择了这个解决方案,因为它似乎更容易)但是,它是可能的。 我正在我的一个项目中构建一个类,其中第三方实用程序需要将CSV行定义为类。

你可以构建代码(我包括\ r \ n,以便我可以读取结果代码):

  string code = "using FileHelpers;\r\n\r\n"; code += "[DelimitedRecord(\"" + delimiter + "\")]\r\n"; code += "public class CustomCSVInputFile "; code += "{ \r\n"; foreach (string column in columnList) { code += " public string " + column.Replace(" ", "") + ";\r\n"; } code += "}\r\n"; CompilerResults compilerResults = CompileScript(code); 

  public static CompilerResults CompileScript(string source) { CompilerParameters parms = new CompilerParameters(); FileHelperEngine engine; parms.GenerateExecutable = false; parms.GenerateInMemory = true; parms.IncludeDebugInformation = false; string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "").Trim(); parms.ReferencedAssemblies.Add(Path.Combine(path, "FileHelpers.dll")); CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp"); return compiler.CompileAssemblyFromSource(parms, source); } 

…就像我提到的那样,如果我不得不重新做一遍,我会调查ExpandoObject,但绝对可以从DataTable创建一个类。 您需要询问列名以构建字段; 我的例子有一个“,”分隔字符串提供的列名列表。

我的例子来自一个非常具体的用例,但如果ExpandoObject不适合你,它应该足以让你继续。