迭代通过可枚举类型的可枚举集合

问题描述:

我想遍历可枚举类型的可枚举集合 但是,我想比较可空类型与内部类型,如字符串或小数。 即这里是一个代码段迭代通过可枚举类型的可枚举集合

 <% 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。

您可以使用静态的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