简体   繁体   English

从Nullable类型的反射中获取PropertyType.Name

[英]Get PropertyType.Name in reflection from Nullable type

I want use reflection for get properties type. 我想使用反射获取属性类型。 this is my code 这是我的代码

var properties = type.GetProperties();
foreach (var propertyInfo in properties)
{
     model.ModelProperties.Add(
                               new KeyValuePair<Type, string>
                                               (propertyInfo.PropertyType.Name,
                                                propertyInfo.Name)
                              );
}

this code propertyInfo.PropertyType.Name is ok but if my property type is Nullable i get this Nullable'1 string and if write FullName if get this stirng System.Nullable1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] 此代码propertyInfo.PropertyType.Name可以,但是如果我的属性类型为Nullable得到此Nullable'1字符串;如果得到此搅动,则得到FullName如果写成System.Nullable1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

Change your code to look for nullable type, in that case take PropertyType as the first generic argument: 更改代码以查找可为空的类型,在这种情况下,将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));

This is an old question, but I ran into this as well. 这是一个老问题,但我也遇到了这个问题。 I like @Igoy's answer, but it doesn't work if the type is an array of a nullable type. 我喜欢@Igoy的答案,但是如果类型是可为null的类型的数组,则它不起作用。 This is my extension method to handle any combination of nullable/generic and array. 这是我的扩展方法,可以处理可为空/通用和数组的任何组合。 Hopefully it will be useful to someone with the same question. 希望它对有相同问题的人有用。

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;
}

This will handle cases as complicated as this: 这将处理如下复杂的情况:

typeof(Dictionary<int[,,],bool?[][]>).GetDisplayName()

Returns: 返回值:

Dictionary<Int32[,,],Boolean?[][]>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM