看到我的问题:
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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望从我的媒体资源创建(如果它是一个类)
如果只想调用无参数构造函数,则可以使用Activator.CreateInstance非常简单。如果您想提供参数或更复杂的参数,它会变得有些毛茸茸,但仍然可行。不过,您之后没有说要对实例做什么:
foreach (var prop in this.GetType().GetProperties())
{
if (prop.PropertyType.IsClass)
{
object instance = Activator.CreateInstance(prop.PropertyType);
// Step 2: ???
// Step 3: Profit!
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2073 次 |
| 最近记录: |