2012-02-25 43 views
0

見我的問題:如何從屬性創建實例這是一個類?

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 
      } 

    } 
    } 
} 

我想從我的房屋創建如果一個類

+0

首先,請用真實的代碼 - C#是區分大小寫;你不能使用「Class」和「Public」,你的意思是「foreach」而不是「freeach」等。其次,你想如何創建一個實例 - 只需調用無參數構造函數? – 2012-02-25 11:30:46

+0

@Jon Skeet我編輯我的問題... – 2012-02-25 11:33:45

回答

4

如果你只想調用參數的構造函數,你可以使用Activator.CreateInstance非常簡單。如果你想提供參數或更復雜的東西,它會變得更輕鬆,但它仍然是可行的。你還沒說你想用實例來以後做什麼,雖然:

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