簡體   English   中英

從Nullable類型的反射中獲取PropertyType.Name

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

我想使用反射獲取屬性類型。 這是我的代碼

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如果寫成System.Nullable1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

更改代碼以查找可為空的類型,在這種情況下,將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));

這是一個老問題,但我也遇到了這個問題。 我喜歡@Igoy的答案,但是如果類型是可為null的類型的數組,則它不起作用。 這是我的擴展方法,可以處理可為空/通用和數組的任何組合。 希望它對有相同問題的人有用。

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?[][]>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM