2012-10-27 22 views
0

最近我正在開發一個小框架爲我自己,
我遇到了這個問題:
我怎樣才能做這樣的事情如下:如何將一個通過反射實例化的對象轉換爲其實際類型?

void object CreateDictionary(Type dictionaryType) 
{ 
    object dict = dictionaryType.GetConstructor(new Type[] {}).Invoke(new object[] {}); 
    // Cast dict to its real type here so that I can add key-value-pairs to it. 
    ... 
} 

的dictionaryType是某種詞典的類型,是通過反思得到的。
我不知道完整類型,因爲直到運行時我才知道泛型屬性。

我也試過將聲明object dict更改爲var dict,但它也不起作用。

回答

1

你不能這樣做。但是,您知道這是某種Dictionary,因此您可以將它轉換爲IDictionary並使用IDictionary的方法。

object CreateDictionary(Type dictionaryType) 
{ 
    object dict = dictionaryType.GetConstructor(new Type[] {}).Invoke(new object[] {}); 
    var idictionary = (IDictionary)dict; 
    idictionary.Add(key, value); 
} 

如果您的所有字典都是從一個類繼承而來,那麼您可以將其轉換爲此類並使用此類的方法。

順便說一句,這是通過簡單拿到類型的實例:

object obj = Activator.CreateInstance(type); 
+0

謝謝,基里爾。 但IDictionary也需要通用屬性。 – Aetherus

+0

有非通用的IDictionary –

0

OK,我設法在最後來解決這個問題。
最後我注意到,我想要做的不是鑄造,
但調用方法。
也許有比我的更好的解決方案。 無論如何,我想分享我的解決方案。

首先,創建一個擴展類對象(這是奇怪,雖然):

public static class ReflectionHelper 
{ 
    public static object InvokeInstanceMethod(this object invoker, string methodName, params object[] parameters) 
    { 
     MethodInfo[] methods = invoker.GetType().GetMethods(); 
     foreach (MethodInfo method in methods) 
     { 
      ParameterInfo[] paramInfos = method.GetParameters(); 
      if (method.Name == methodName && paramInfos.Length == parameters.Length) 
      { 
       for (int i = 0; i < parameters.Length; i++) 
       { 
        if (!paramInfos[i].ParameterType.IsAssignableFrom(parameters[i].GetType())) 
        { 
         throw new MissingMethodException(); 
        } 
       } 
       return method.Invoke(invoker, parameters); 
      } 
     } 
     throw new MissingMethodException(); 
    } 
} 

這種擴展方法可以讓我這樣調用方法:

anyInstance.InvokeInstanceMethod("MethodName", param1, param2, ...); 

因爲所有類型,排除對象本身,都是從Object派生的,這個方法可以在任何類型的任何實例上調用。

然後我用這個方法:

object dict = dictionaryType.CreateInstance(); // The method CreateInstance() is also an extension 
dict.InvokeInstanceMethod("Add", key, val); 
相關問題