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

标签 c# .net asp.net-mvc nullable

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

       <% 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()); %>

关于c# - 遍历具有可为空类型的 Enumerable 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1482377/

相关文章:

c# - 从不同的代码隐藏更改 ascx 内容

.net - 添加节点后自动对TreeView进行排序

.net - MS 考试 70-536 - 如何从线程中抛出和处理异常?

c# - Elastic Search Nest-比较两个字段

c# - WinRT IBackgroundTask 不会运行

jquery - 是否可以将 SimpleModal 与 ASP.NET MVC 一起使用?

asp.net-mvc - 如何在 MVC 应用程序中缓存数据

c# - 渲染不同的局部 View onclick 不同的按钮

c# - 推荐XNA教程开始学习3D(第一次)

c# - C# 中 Func<in T, bool> 的运算符