生成空对象 - 具有空属性/子类的空类C#

Mun*_*uno 5 c# empty-class

我有两节课:

public class HumanProperties { int prop1; int prop2; string name;}

public class Human{int age; HumanProperties properties;}
Run Code Online (Sandbox Code Playgroud)

现在,如果我想创建人类的新实例,我必须这样做Human person = new Human(); 但是当我尝试访问时,我person.properties.prop1=1;在属性上有nullRefrence,因为我也必须创建新属性.我必须这样做:

Human person = new Human();
person.properties = new HumanProperties();
Run Code Online (Sandbox Code Playgroud)

现在我可以访问它 person.properties.prop1=1;

这是一个小例子,但我有从xsd生成的巨大类,我没有那么多时间手动生成这个"人"类及其所有子类.有什么方法可以通过编程方式进行,还是有一些生成器呢?

或者我可以循环遍历类并为每个属性创建新类typeof属性并将其加入父类?

谢谢!

Ere*_*mez 7

作为类的默认类型,我没有传统方法来执行您要求的操作null.但是,您可以使用反射以递归方式遍历属性,使用无参数构造函数查找公共属性并初始化它们.这样的东西应该工作(未经测试):

void InitProperties(object obj)
{
    foreach (var prop in obj.GetType()
        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .Where(p => p.CanWrite))
    {
        var type = prop.PropertyType;
        var constr = type.GetConstructor(Type.EmptyTypes); //find paramless const
        if (type.IsClass && constr != null)
        {
            var propInst = Activator.CreateInstance(type);
            prop.SetValue(obj, propInst, null);
            InitProperties(propInst);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以这样使用:

var human = new Human();
InitProperties(human); 
Run Code Online (Sandbox Code Playgroud)


Jen*_*ter 5

我建议你使用构造函数:

public class Human
{
  public Human()
  {
     Properties = new HumanProperties();
  }

  public int Age {get; set;} 
  public HumanProperties Properties {get; set;}
}
Run Code Online (Sandbox Code Playgroud)