Creating a dynamic class in C #

Is it possible at runtime to create a class from a DataTable where ColumnName will be the properties of a dynamic class?

+5
source share
5 answers

With C # 4 you can do it

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

Do not recommend it or anything else, but it shows that it is possible.

+4
source

Yes (using Reflection.Emit), but this is a bad idea.
What are you trying to do?

+1
source

, , . 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);
        }        
    }
+1

# 4, ExpandoObject. .

+1

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. ; , .,

My example is from a very specific use case, but that should be enough so that you can work if ExpandoObject does not work for you.

0
source

All Articles