Get PropertyType.Name in reflection from Nullable type

前端 未结 2 1783
悲&欢浪女
悲&欢浪女 2020-12-30 09:45

I want use reflection for get properties type. this is my code

var properties = type.GetProperties();
foreach (var propertyInfo in properties)
{
     model.         


        
相关标签:
2条回答
  • 2020-12-30 10:21

    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. 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?[][]>
    
    0 讨论(0)
  • 2020-12-30 10:26

    Change your code to look for nullable type, in that case take PropertyType as the first generic argument:

    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));
    
    0 讨论(0)
提交回复
热议问题