2012-02-25 15 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 
      } 

    } 
    } 
} 

私はあなたが唯一のパラメータなしのコンストラクタを呼び出したい場合は、あなたは非常に簡単Activator.CreateInstanceを使用することができ、そのクラス

+0

は、実際のコードを使用してください - C#は大文字と小文字が区別されます。 「クラス」と「パブリック」を使用することはできません。「フリーハンド」などの代わりに「foreach」を意味します。次に、インスタンスを作成する方法 - パラメータのないコンストラクタを呼び出すだけですか? –

+0

@Jon Skeet私の質問を編集する... –

答えて

4

場合は私の財産から作成したいと思います。引数やもっと複雑なものを提供したい場合は、少し毛がかかっていますが、まだ実行可能です。

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