Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用可为null的类型遍历可枚举集合_C#_.net_Asp.net Mvc_Nullable - Fatal编程技术网

C# 使用可为null的类型遍历可枚举集合

C# 使用可为null的类型遍历可枚举集合,c#,.net,asp.net-mvc,nullable,C#,.net,Asp.net Mvc,Nullable,我试图迭代一个可枚举的可空类型的混合集合 但是,我想将可空类型与内在类型(如string或decimal)进行比较。 i、 这里有一个片段 <% foreach (PropertyInfo prop in this.Columns) { %> <td> <% var typeCode = Type.GetTypeCode(prop.PropertyType); %> <%--

我试图迭代一个可枚举的可空类型的混合集合 但是,我想将可空类型与内在类型(如string或decimal)进行比较。 i、 这里有一个片段

       <% 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进行比较时,它失败了。 有没有办法将可空类型解析为其基础类型,e、 确定日期时间?到datetime。

您可以使用静态方法。为了便于使用,我可能会将其包装在扩展方法中:

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;
}
公共静态类型GetUnderlineType(此类型源)
{
if(source.IsGenericType
&&(source.GetGenericTypeDefinition()==typeof(可空)))
{
//源是可为null的类型,因此返回其基础类型
返回Nullable.GetUnderlyingType(源);
}
//源不是可为null的类型,因此只需返回原始类型
返回源;
}
您需要更改示例代码,使其看起来像这样:

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

您可以使用静态方法。为了便于使用,我可能会将其包装在扩展方法中:

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;
}
公共静态类型GetUnderlineType(此类型源)
{
if(source.IsGenericType
&&(source.GetGenericTypeDefinition()==typeof(可空)))
{
//源是可为null的类型,因此返回其基础类型
返回Nullable.GetUnderlyingType(源);
}
//源不是可为null的类型,因此只需返回原始类型
返回源;
}
您需要更改示例代码,使其看起来像这样:

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