gpt4 book ai didi

c# - 如何在不知道键类型和值类型的情况下遍历 KeyValuePair 的枚举

转载 作者:太空狗 更新时间:2023-10-29 23:20:09 24 4
gpt4 key购买 nike

假设我有这样的方法:

public void Foo(object arguments)

然后说我需要检测 arguments 的类型实际上是一个枚举。我会这样写:

if (arguments is IEnumerable)

现在,假设我需要检测它是否是 KeyValuePair 的枚举(无论键的类型和值的类型如何)。我的直觉是写这样的东西:

if (arguments is IEnumerable<KeyValuePair<,>>)

但 visual studio 提示 Using the generic type 'KeyValuePair<TKey, TValue>' requires 2 type arguments .

我也试过:

if (arguments is IEnumerable<KeyValuePair<object, object>>)

但如果键不是对象(例如 string)或者值不是对象(例如 int),则返回 false。

有没有人建议我如何确定一个枚举是否包含 KeyValuePairs 而不管键类型和值类型,如果是,我如何遍历这些对?

最佳答案

你需要在这里反射(reflection)一下:

Boolean isKeyValuePair = false;

Type type = arguments.GetType();

if (type.IsGenericType)
{
Type[] genericTypes = type.GetGenericArguments();

if (genericTypes.Length == 1)
{
Type underlyingType = genericTypes[0];

if (underlyingType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
isKeyValuePair = true;
}
}

为了重建一个 Enumerable 并对其进行迭代,您可以使用以下使用 dynamic 的方法:

List<KeyValuePair<Object, Object>> list = new List<KeyValuePair<Object, Object>>();

foreach (dynamic kvp in (IEnumerable)arguments)
list.Add(new KeyValuePair<Object, Object>(kvp.Key, kvp.Value));

或者,使用 LINQ:

List<KeyValuePair<Object, Object>> list = (from dynamic kvp in (IEnumerable)arguments select new KeyValuePair<Object, Object>(kvp.Key, kvp.Value)).ToList();

我还找到了另一个解决方案,但这纯粹是疯狂的:

Boolean isKeyValuePair = false;

Type type = arguments.GetType();

if (type.IsGenericType)
{
Type[] genericTypes = type.GetGenericArguments();

if (genericTypes.Length == 1)
{
Type underlyingType = genericTypes[0];

if (underlyingType.GetGenericTypeDefinition() == typeof (KeyValuePair<,>))
{
Type[] kvpTypes = underlyingType.GetGenericArguments();

Type kvpType = typeof(KeyValuePair<,>);
kvpType = kvpType.MakeGenericType(kvpTypes);

Type listType = typeof (List<>);
listType = listType.MakeGenericType(kvpType);

dynamic list = Activator.CreateInstance(listType);

foreach (dynamic argument in (IEnumerable)arguments)
list.Add(Activator.CreateInstance(kvpType, argument.Key, argument.Value));
}
}
}

引用资料:

关于c# - 如何在不知道键类型和值类型的情况下遍历 KeyValuePair 的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48016978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com