Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从类的属性创建实例?_C# - Fatal编程技术网

C# 如何从类的属性创建实例?

C# 如何从类的属性创建实例?,c#,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

看看我的问题:

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
          }

     }
  }
}

如果它是一个类,我想从我的属性创建。如果你只想调用无参数构造函数,你可以非常简单地使用。如果你想提供论据或更复杂的东西,它会稍微复杂一些,但它仍然是可行的。不过,您还没有说明以后要对该实例执行什么操作:

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

使用Assembly.CreateInstance方法:


首先,请使用实代码-C区分大小写;你不能使用“Class”和“Public”,你的意思是“foreach”而不是“freeach”等等。其次,你想如何创建一个实例——只需调用无参数构造函数?@Jon Skeet我编辑我的问题。。。