Получить PropertyType.Name в отражении от Nullable типа
Я хочу использовать отражение для типа свойств.
это мой код
var properties = type.GetProperties();
foreach (var propertyInfo in properties)
{
model.ModelProperties.Add(
new KeyValuePair<Type, string>
(propertyInfo.PropertyType.Name,
propertyInfo.Name)
);
}
этот код propertyInfo.PropertyType.Name
в порядке, но если мой тип свойства Nullable
, я получаю эту строку Nullable'1
, и если напишу FullName
, если получится это stirng System.Nullable1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
Ответы
Ответ 1
Измените свой код, чтобы искать тип с нулевым значением, в этом случае возьмите PropertyType в качестве первого общего агенмента:
var propertyType = propertyInfo.PropertyType;
if (propertyType.IsGenericType &&
propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyType = propertyType.GetGenericArguments()[0];
}
model.ModelProperties.Add(new KeyValuePair<Type, string>
(propertyType.Name,propertyInfo.Name));
Ответ 2
Это старый вопрос, но я тоже столкнулся с этим. Мне нравится @Igoy ответ, но он не работает, если type является массивом типа NULL. Это мой метод расширения для обработки любой комбинации значений NULL/generic и array. Надеюсь, это будет полезно кому-то с тем же вопросом.
public static string GetDisplayName(this Type t)
{
if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
return string.Format("{0}?", GetDisplayName(t.GetGenericArguments()[0]));
if(t.IsGenericType)
return string.Format("{0}<{1}>",
t.Name.Remove(t.Name.IndexOf('`')),
string.Join(",",t.GetGenericArguments().Select(at => at.GetDisplayName())));
if(t.IsArray)
return string.Format("{0}[{1}]",
GetDisplayName(t.GetElementType()),
new string(',', t.GetArrayRank()-1));
return t.Name;
}
Это относится к таким сложным случаям, как это:
typeof(Dictionary<int[,,],bool?[][]>).GetDisplayName()
Возврат:
Dictionary<Int32[,,],Boolean?[][]>