动态创建 C# 类或对象

Muh*_*BUL 6 c# properties dynamic

我有这个结构。

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.
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,我想从“GetFoo()”函数为“Foo”类创建属性。同时,该函数返回“List”“Foo”类型。我正在研究“在运行时动态添加 C# 属性”“如何在 C# 中动态创建类?” 但这些链接中的答案不会被引用为返回值或引用另一个类。我怎样才能做到这一点?

luc*_*cky 0

你为什么不直接使用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 };
}
Run Code Online (Sandbox Code Playgroud)

在运行时为类添加属性是不可能执行的。