如何获取通用 IDictionary<,>
的键值使用反射。
这就是我想做的事情。
public static string Format<T>(T item)
{
if (item.GetType().GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IDictionary<,>)))
{
// I know it's a IDictionary so figure out what the types are
Type keyType = item.GetType().GetGenericArguments()[0];
Type valueType = item.GetType().GetGenericArguments()[1];
//Now cast it to the correct IDictionary. How do I properly inject the type here?
var keyList = ((IDictionary<keyType, valueType>)item).Select(x => x.Key.ToString()).ToArray<string>();
}
}
编辑:澄清我想使用反射
最佳答案
我认为你把事情复杂化了。当我查看您的代码时,您正在尝试执行以下操作:
myDictionary.Keys.Select(k => k.ToString()).ToArray();
所以,
public string Format<T>(T value) {
if (##item is dictionary) {
var items = name.GetType().GetProperty("Keys", BindingFlags.Instance | BindingFlags.Public).GetValue(item) as IEnumerable;
if (items == null) throw new ArgumentException("Dictionary with no keys?");
string[] data = items.OfType<object>().Select(o => o.ToString()).ToArray();
}
}
关于c# - 使用反射获取通用 Dictionary <,> 的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29995883/