Skip to main content
 首页 » 编程设计

c#之遍历具有可为空类型的 Enumerable 集合

2024年02月24日27cyq1162

我正在尝试迭代可空类型混合的可枚举集合 但是,我想将可空类型与内部类型(如字符串或小数)进行比较。 即这是一个片段

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

prop.PropertyType 是“datetime?”类型,但是 var typeCode 是“object”。所以当我将 typeCode 与 TypeCode.String 进行比较时,它失败了。 有没有办法将可空类型解析为其基础类型? ,例如解析日期时间?到日期时间。

请您参考如下方法:

您可以使用静态 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()); %>