繁体   English   中英

C#中的动态类创建

[英]Dynamic class creation in C#

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

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

dynamic foo = new ExpandoObject();

// mimic grabbing a column name at runtime and adding it as a property
((IDictionary<string, object>)foo).Add("Name", "Apple");

Console.WriteLine(foo.Name); // writes Apple to screen

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

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

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

public class DynClass<T, P>
    {
        public DynClass()
        {
            _fields = new Dictionary<T, P>();
        }

        private IDictionary<T, P> _fields;

        public IDictionary<T, P> 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<string, object>
             * */
            DynClass<string, Client> gen = new DynClass<string, Client>();

            /* Add the fields
             * */
            gen.Fields.Add("clientName", cli);

            /* Add the objects to the List
             * */
            List<object> lstDyn = new List<object>().Add(gen);
        }        
    }

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

我将要查看上面提到的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不适合你,它应该足以让你继续。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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