星期三, 11月 29, 2006

透過reflection機制初始化Field物件

一般來說,初始化Field必須要在定義時做,如:

class TestClass{
private static StringBuilder sb = new StringBuilder();
private static StringBuilder sb2 = new StringBuilder();
}

如果需要三不五時重設這些Field,可能會加上如下的Method:


class TestClass{
private static StringBuilder sb = new StringBuilder();
private static StringBuilder sb2 = new StringBuilder();
public static void ReInit(){
sb = new StringBuilder();
sb2 = new StringBuilder();
}
}

如果之後又有sb3, sb4, ....., sbn,那麼每加一個都得記得去修改ReInit()。不但不方便,還可能忘記。可能的解決方法是利用.NET Reflection機制,查出有哪些Field,然後再根據Field的型別去建立物件。以下範例示範初始化所有static fields (假設所有類別都有不含參數的constructor):


FieldInfo[] fs = typeof(TestClass).GetFields(BindingFlags.Static | BindingFlags.NonPublic);
foreach (FieldInfo f in fs)
{
if (f.IsStatic)
{
object obj = f.FieldType.Assembly.CreateInstance(f.FieldType.FullName);
f.SetValue(null, obj);
}
}