2016-08-30 32 views
0
Type type_class_a = ....; 
Type type_class_b = type_class_a.GetField("name_b").FieldType; 
MethodInfo method = type_class_b.GetMethod("method"); 
method.Invoke(type_class_b,new object[] {"test_string"}); 

裏面,但我得到的錯誤反思:在DLL</p> <pre><code>public class class_a { public static class_b name_b = new class_b(); } public class class_b { public void method(string data) { } } </code></pre> <p>調用方法靜態字段

型 'System.Reflection.TargetException' 未處理的異常出現在mscorlib.dll 其他信息:對象與目標類型不匹配。

那麼如何調用它呢? Thankyou。

+2

'method.Invoke'的第一個參數應該是'class_b'的*實例*,而不是類型。你正在調用一個實例方法 - 你仍然需要一個實例。 – Blorgbeard

+0

謝謝,它的工作。 'var instance = Activator.CreateInstance(type_class_b); type_class_a.GetField(「name_b」)。SetValue(type_class_a,instance)' –

+0

使用Activator.CreateInstance(...)創建實例時,會在內存中創建另一個對象。因此,如果您的'class_a'的靜態成員'name_b'存儲在內存位置0x1234,則使用Activator.CreateInstance創建的對象將不是該對象,而是可能存儲在內存地址0x9876的新對象。因此,您可能沒有使用Activator.CreateInstance創建的此對象中的字段和屬性的值相同;而且這也會導致很多耗時的調試時間(因爲你將無法確定值的丟失位置) –

回答

1

隨着你class_a類定義class_b類型和class_b的對象包含一個方法命名method,你的方法將作爲(在DLL)

  1. 獲取class_a對象的Type在代碼(在class_a_type存儲如下Type型)
  2. 獲取class_a_type對象的FieldInfo對象name_b對象(存儲它在類型的a_field_info可變的可變10)字段類型(在你的案件
  3. 獲取對象,在對象的對象實例name_b)通過調用FieldInfo對象的getValue函數(其存儲在object型)b_object可變
  4. 獲取MethodInfo對象爲方法通過調用b_object.GetType().GetMethod("method")(名爲method)在上述b_object對象(並將其存儲在MethodInfo類型的b_method對象)通過調用上述b_method對象上Invoke功能和傳遞b_object作爲第一個參數(
  5. 調用方法作爲第二個參數(要傳遞給該函數的參數數組)的參數null

有點混亂?找到下面的例子:

Type class_a_type = class_a_object.GetType(); 
FieldInfo a_field_info = class_a_type.GetField("name_b"); 

object b_object = a_field_info.GetValue(class_a_object); 
MethodInfo b_method = b_object.GetType().GetMethod("method"); 

b_method.Invoke(b_object, null); 

希望幫助!

0

一旦獲得了name_b的FieldInfo,就需要調用FieldInfo.GetValue(null)來獲取實際值(class_b的實例)。您還需要typeof(class_b).method的MethodInfo。

一旦你有了這兩個,你可以在class_b的實例中調用methodInfo.Invoke傳遞。

相關問題