Dynamically Create C# Class or Object

柔情痞子 提交于 2019-12-11 02:29:13

问题


I have this structure.

public class FirstClass
{
   public List<Foo> FooList{ get; set; }
}

public class Foo{
   //Ex:
   //public string Name{ get; set; }  
}

public List<Foo> GetFoo(){
//I'm use Firstclass like this here typeof(FirstClass);
//I want create here dynamic property for Foo class.
}

And my problem is, i want create property for "Foo" class from "GetFoo()" function. Same time, this function return "List" "Foo" type. I'm research "Dynamically Add C# Properties at Runtime", "How to dynamically create a class in C#?" but the answers in these links are not referenced as return values or referenced to another class. How i can do this?


回答1:


You can dynamically create classes, which inherits Foo, with any additional properties. Thus you can add instances of those dynamic classes into List<Foo>.

To do so, one can generate a code string like following:

var bar1Code = @"
public class Bar1 : Foo
{
    public Bar1(int value)
    {
        NewProperty = value;
    }
    public int NewProperty {get; set; }
}
";

Then compile it using CSharpCodeProvider:

var compilerResults = new CSharpCodeProvider()
    .CompileAssemblyFromSource(
        new CompilerParameters
        {
            GenerateInMemory = true,
            ReferencedAssemblies =
            {
                "System.dll",
                Assembly.GetExecutingAssembly().Location
            }
        },
        bar1Code);

Then one can create an instance of Bar1, add it to List<Foo> and, e.g. cast it to dynamic to access the dynamic property:

var bar1Type = compilerResults.CompiledAssembly.GetType("Bar1");
var bar2Type = compilerResults.CompiledAssembly.GetType("Bar2"); // By analogy

var firstClass = new FirstClass
{
    FooList = new List<Foo>
    {
        (Foo)Activator.CreateInstance(bar1Type, 56),
        (Foo)Activator.CreateInstance(bar2Type, ...)
    }
};

var dynamicFoo = (dynamic)firstClass.FooList[0];
int i = dynamicFoo.NewProperty; // should be 56



回答2:


Why don't you just use a Dictionary;

public class Foo
{
    public Dictionary<string, object> Properties;

    public Foo()
    {
        Properties = new Dictionary<string, object>();
    }
}
public List<Foo> GetFoo()
{
    var item = new Foo();
    item.Properties.Add("Name","Sample");
    item.Properties.Add("OtherName", "Sample");
    return new List<Foo>{ item };
}

Adding property for a class in runtime, it is not possible to perform.



来源:https://stackoverflow.com/questions/47767871/dynamically-create-c-sharp-class-or-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!