在C#中使用泛型获取字典的类型名称

问题描述 投票:0回答:2

有没有一种简单或优雅的方法来获取具有 C# 中泛型类型的字典的类型名称?

目前我可以使用此代码:

if (property.PropertyType.Name == "Dictionary`2")
{
    Type[] arguments = property.PropertyType.GetGenericArguments();
    Type keyType = arguments[0];
    Type valueType = arguments[1];
    properties[property.Name] = $"Dictionary<{keyType.Name},{valueType.Name}>";
}

我想知道是否有更简单的方法来实现我正在寻找的格式化字符串,例如:“Dictionary

c# types reflection
2个回答
0
投票

为什么你认为你的方法并不“容易”?

您知道泛型字典constantly的类型“name”为

Dictionary<TKey, TValue>
,只有2个泛型参数。例如:

 const string GenericDictionaryTypeName = "Dictionary<TKey, TValue>";
 // ...
 properties[propertyName] = GenericDictionaryTypeName;

如果您出于任何原因想要将 4 行缩短为 1 行 - 您可以使用

string.Join
并传递使用 LINQ 的
Select
所采用的泛型参数类型名称:

properties[propertyName] = $"Dictionary<{string.Join(", ", property.PropertyType.GetGenericArguments().Select(t => t.Name))}>"

但是由于单行代码很长,你会失去可读性。


0
投票

我建议使用递归,即

private static string MyTypeName(Type type) {
  if (type.IsArray)
    return $"{MyTypeName(type.GetElementType())}[]";

  if (type.IsGenericTypeDefinition)
    return type.Name[0..type.Name.IndexOf('`')];
  if (type.IsGenericType) 
    return $"{MyTypeName(type.GetGenericTypeDefinition())}<{string.Join(", ", type.GenericTypeArguments.Select(t => MyTypeName(t)))}>";

  return type.Name;
}

演示:

var type = typeof(Dictionary<int, HashSet<string>[]>[][]);

Console.Write(MyTypeName(type));

输出:

Dictionary<Int32, HashSet<String>[]>[][]
© www.soinside.com 2019 - 2024. All rights reserved.