c# - 使用反射获取通用 Dictionary <,> 的键值

标签 c#

如何获取通用 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/

相关文章:

c# - 为什么你仍然可以使用已处置的对象?

C#:如何从某种文化中获取资源字符串

c# - LISP 中的关联列表是否与 C# 中的字典相同?

c# - 确定几何形状层次结构所需的算法

c# - 创建和使用类名仅在运行时已知的类的实例

c# - Entity Framework 原始 SQL 查询

c# - 无法在 C# 中隐式转换类型 'System.Collections.Generic.List<AnonymousType#1>

c# - 鼠标悬停按钮时无法更改边框颜色

c# - System.Net.Sockets.Tcpclient.Connect 错误 <String hostname, Int32 port>

c# - SignalR:如何在页面重新加载时停止创建新连接