如何从属性创建实例这是一个类?

时间:2012-02-25 11:28:25

标签: c#

看我的问题:

public class Address
{
public string Title{get;set;}
public string Description{get;set;}
}
public class Tell
{
 public string Title{get;set;}
 public string Number{get;set;}
}
 public class Person
{
 public string FirstName{get;set;}
 public string LastName{get;set;}
 public Address PAddress {get;set;}
 public Tell PTell {get;set;}

 void CreateInstanceFromProperties()
  {
    foreach(var prop in this.GetType().GetProperties())
     {
       if(prop.PropertyType.IsClass)
          {
            //Create Instance from this property
          }

     }
  }
}

我希望从我的属性创建,如果它是一个类

2 个答案:

答案 0 :(得分:5)

如果您只想调用无参数构造函数,则可以非常简单地使用Activator.CreateInstance。如果你想提供更复杂的参数或更复杂的东西,它会变得更加毛茸茸,但它仍然可行。之后您还没有说过要对实例做什么:

foreach (var prop in this.GetType().GetProperties())
{
     if (prop.PropertyType.IsClass)
     {
         object instance = Activator.CreateInstance(prop.PropertyType);
         // Step 2: ???
         // Step 3: Profit!
     }
}

答案 1 :(得分:1)