2010-08-11 135 views
18

我想創建一個靜態類,它將從XML文件加載一些設置並將這些設置應用於其自己的屬性。使用靜態類反射設置屬性

我想使用下面的代碼,但我真的不知道要給SetValue方法什麼,因爲我們要爲其設置屬性的類是靜態的。

// some code removed ... 
Type settingsType = typeof(Settings); // Settings is a static class 

foreach (PropertyInfo propertyInformation in settingsType.GetProperties(BindingFlags.Public | 
            BindingFlags.Static)) 
{ 
     //------------------------------------------------------------ 
     // Determine if configured setting matches current setting based on name 
     //------------------------------------------------------------ 
     if (propertyInformation.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) 
     { 
     //------------------------------------------------------------ 
     // Attempt to apply configured setting 
     //------------------------------------------------------------ 
     try 
     { 
     if (propertyInformation.CanWrite) 
     { 
     propertyInformation.SetValue(this, Convert.ChangeType(value, propertyInformation.PropertyType, CultureInfo.CurrentCulture), null); 
     } 
     } 
     catch 
     { 
     } 
      break; 
     } 

}

它甚至有可能對靜態類與反思設置屬性?

+0

'設置'是**'內部密封的部分類設置'**? – 2016-08-04 08:26:33

回答

30

只是通過null爲例。

+2

使用「typeof(設置)」代替「this」也可以使用 – mare 2010-08-12 00:07:58

+0

@mare:可能會被靜態成員忽略。 – leppie 2010-08-12 04:02:31

+0

根據文檔,它被忽略,所以你可以傳遞任何東西。爲了便於閱讀,我們通常這樣稱呼它: ''' prop.SetValue(「ThisArgumentIsIgnoredForStaticMethods」,value); ''' – 2018-02-05 21:37:55