如何分辨C#中的typeof(int)== typeof(int?)之间的区别

时间:2018-08-01 14:37:35

标签: c#

为什么C#将这些设置为相等?

.Add()

在将表达式树转换为

的位置写表达式树时会发生问题
typeof(int).GetType() == typeof(int?).GetType()

产生此错误

  

System.ArgumentException:类型'System.Int32'的表达式不能用于类型'System.Nullable List<int?> ids = JsonConvert.DeserializeObject<List<int?>>(filter.Value?.ToString()); var filterField = filter.PropertyName; var method = ids.GetType().GetMethod("Contains"); return Expression.Call(Expression.Constant(ids), method, member); 1 [System.Int32])

是否可以在发送到表达式树之前检查类型?

我尝试检查1[System.Int32]' of method 'Boolean Contains(System.Nullableint的类型,并为以下检查均返回true:

int?

5 个答案:

答案 0 :(得分:10)

  

为什么C#将这些设置为相等?

因为它们相等。

typeof(int)由编译器生成RuntimeType实例

typeof(int?)由编译器生成不同 RuntimeType实例

在任何GetType()实例上调用RuntimeType都会返回类型System.RuntimeType

我认为你想要

typeof(int) == typeof(int?)

bool isIntNull = type.Equals(typeof(int?));

证明:

Console.WriteLine(typeof(int));
Console.WriteLine(typeof(int?));
Console.WriteLine(typeof(int).GetType());
Console.WriteLine(typeof(int?).GetType());

输出:

System.Int32
System.Nullable`1[System.Int32]
System.RuntimeType
System.RuntimeType

答案 1 :(得分:1)

typeof(X)运算符始终返回代表类型Type的{​​{1}}对象。 X方法返回调用它的对象的运行时类型。因此,如果您拥有表达式GetType(),则表达式的第一部分将始终返回一个typeof(X).GetType()实例,而该表达式的第二部分将始终返回一个表示类型{{ 1}},无论Type是什么。您想将TypeType进行比较。

答案 2 :(得分:1)

我认为,您的表达式树有一个问题,就是member变量是类型Expression的{​​{1}}而不是int。 您发布的代码未显示其来源,但我认为以下内容对您有帮助:

int?

答案 3 :(得分:0)

在找到答案并在这里进行了所有尝试之后,找到了这个。

bool isIntNull = member.Type.IsGenericType && member.Type.GetGenericTypeDefinition() == typeof(Nullable<>);

答案 4 :(得分:0)

将未知的运行时数据类型的数据提取为已知的数据类型时,我遇到了同样的问题-我用这种方法解决了这个问题。

public bool CompareDataType<T>(Type runtimedatatype)
{
    Type KT = typeof(T);

    return runtimedatatype.Equals(KT) || runtimedatatype.Equals(Nullable.GetUnderlyingType(KT));
}

int? output = null;
object RunTimeData = (object)((int)0);
if (CompareDataType<int?>(RunTimeData.GetType()))
    output = (int?)RunTimeData;

或者,您可以创建Object的扩展(这是我最后使用的扩展)

public static class ObjectTypeIsEqual
{
    public static bool CompareDataType<T>(this object input)
    {
        Type ObjectType = input.GetType();
        Type CompareType = typeof(T);

        return ObjectType.Equals(CompareType) || ObjectType.Equals(Nullable.GetUnderlyingType(CompareType));
    }
}

int? output = null;
object RunTimeData = (object)((int)0);
if (RunTimeData.CompareDataType<int?>())
    output = (int?)RunTimeData;