2009-09-26 119 views
1

我想遍歷可枚舉類型的可枚舉集合 但是,我想比較可空類型與內部類型,如字符串或小數。 即這裏是一個代碼段迭代通過可枚舉類型的可枚舉集合

 <% foreach (PropertyInfo prop in this.Columns) 
     { %> 
     <td> 
     <% var typeCode = Type.GetTypeCode(prop.PropertyType); %> 


     <%-- String Columns --%> 
     <% if (typeCode == TypeCode.String) 
      { %> .... 

prop.PropertyType的類型爲「日期時間?」,但是無功TYPECODE是「object'.So當我比較TYPECODE到TypeCode.String,它失敗。 有沒有辦法將可空類型解析爲它的基礎類型?如解析日期時間?到datetime。

回答

4

您可以使用靜態的Nullable.GetUndlerlyingType方法。我可能會包裝在一個擴展方法的易用性:

public static Type GetUnderlyingType(this Type source) 
{ 
    if (source.IsGenericType 
     && (source.GetGenericTypeDefinition() == typeof(Nullable<>))) 
    { 
     // source is a Nullable type so return its underlying type 
     return Nullable.GetUnderlyingType(source); 
    } 

    // source isn't a Nullable type so just return the original type 
    return source; 
} 

你需要改變你的示例代碼看起來是這樣的:

<% var typeCode = Type.GetTypeCode(prop.PropertyType.GetUnderlyingType()); %> 
+0

那做的人,謝謝! – D0cNet 2009-09-27 03:15:49