2015-01-20 23 views
0
的空默認構造函數

我想實例化我的對象上的每個屬性(類型JobVmInput)。 這是我到目前爲止的代碼:調用類型爲

var properties = this.GetType().GetProperties(); 

foreach (var p in properties) 
{ 
    var type = p.PropertyType; 
    if (type.IsSubclassOf(typeof(JobVmInput))) 
    { 
      var constructor = type.cons.GetConstructor(**what to input here**); 
      p.SetValue(p, constructor.Invoke(**what to input here**)); 
    } 
} 

但是我不知道是什麼在GetConstructor和constructor.Invoke方法輸入。我查看了MSDN文檔,但我很不確定他們接受了什麼。我只想調用空的默認構造函數。

回答

4

您可以使用:

var constructor = type.GetConstructor(Type.EmptyTypes); 
p.SetValue(this, constructor.Invoke()); 

或者:

p.SetValue(this, Activator.CreateInstance(type)); 

請注意,我已經取代第一個參數this因爲SetValue方法需要您object不是PropertyInfo

+0

感謝的一個實例它非常棒! – JensOlsen112 2015-01-20 19:58:21

相關問題