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 是某种 Dictionary 的类型,是通过反射得到的。
我不知道完整类型,因为直到运行时我才知道通用属性。

我也尝试将声明更改object dictvar dict,但它也不起作用。

4

2 回答 2

1

你不能做这个。但是,您知道这是某种字典,因此您可以将其转换为 IDictionary 并使用 IDictionary 的方法。

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

如果您的所有这些字典都是从一个类继承的,则可以将其强制转换为该类并使用该类的方法。

顺便说一句,通过以下方式获取 Type 的实例更简单:

object obj = Activator.CreateInstance(type);
于 2012-10-27T12:49:30.500 回答
0

好的,我终于设法解决了这个问题。
最后我注意到我想做的不是强制转换,
而是调用方法。
也许有比我更好的解决方案。无论如何,我想分享我的解决方案。

首先,为对象创建一个扩展类(虽然这很奇怪):

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 派生的,因此可以在任何类型的任何实例上调用此方法。

然后我使用这个方法:

object dict = dictionaryType.CreateInstance(); // The method CreateInstance() is also an extension
dict.InvokeInstanceMethod("Add", key, val);
于 2012-10-27T12:53:06.347 回答