我有一个实现的实例IDictionary<T, K>
,我在编译时不知道T和K,想从中获取所有元素。我不想使用IEnumerable
由于某种原因,这将是唯一实现的非通用接口IDictionary
.
到目前为止我的代码:
// getting types
Type iDictType = instance.GetType().GetInterface("IDictionary`2");
Type keyType = iDictType.GetGenericArguments()[0];
Type valueType = iDictType.GetGenericArguments()[1];
// getting the keys
IEnumerable keys = (IEnumerable)dictType.GetProperty("Keys")
.GetValue(instance, null);
foreach (object key in keys)
{
// ==> this does not work: calling the [] operator
object value = dictType.GetProperty("Item")
.GetValue(instance, new object[] {key } );
// getting the value from another instance with TryGet
MethodInfo tryGetValue = iDictType.GetMethod("TryGetValue");
object[] arguments = new object[] { key, null };
bool hasElement = (bool)tryGetValue.Invoke(otherInstance, arguments);
object anotherValue = arguments[1];
}
我也可以调用 TryGetValue,但我认为应该可以调用 [] 运算符。有谁能够帮助我?
最好是弄清楚 the TKey
/ TValue
,并通过切换到常规代码MakeGenericMethod
- 像这样:
(edit- 你可以通过otherInstance
也作为参数,如果它们属于同一类型)
static class Program
{
static void Main()
{
object obj = new Dictionary<int, string> {
{ 123, "abc" }, { 456, "def" } };
foreach (Type iType in obj.GetType().GetInterfaces())
{
if (iType.IsGenericType && iType.GetGenericTypeDefinition()
== typeof(IDictionary<,>))
{
typeof(Program).GetMethod("ShowContents")
.MakeGenericMethod(iType.GetGenericArguments())
.Invoke(null, new object[] { obj });
break;
}
}
}
public static void ShowContents<TKey, TValue>(
IDictionary<TKey, TValue> data)
{
foreach (var pair in data)
{
Console.WriteLine(pair.Key + " = " + pair.Value);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)