繁体   English   中英

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

[英]How to tell the difference between typeof(int) == typeof(int?) in C#

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

typeof(int).GetType() == typeof(int?).GetType()

在将表达式树强制转换为

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

产生这个错误

System.ArgumentException:类型'System.Int32'的表达式不能用于1[System.Int32]' of method 'Boolean Contains(System.Nullable 1 [System.Int32])的类型'System.Nullable 1[System.Int32]' of method 'Boolean Contains(System.Nullable参数

有没有一种方法可以在发送到表达式树之前检查类型?

我尝试检查intint?的类型int? 并为以下检查返回true:

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

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

因为他们是平等的。

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

typeof(int?)由编译器生成另一个 RuntimeType实例

在任何RuntimeType实例上调用GetType()都会返回类型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

typeof(X)运算符始终返回表示X Type对象。 GetType()方法返回调用它的对象的运行时类型。 所以,如果你有表达typeof(X).GetType()第一个表达式将始终返回的部分Type的实例,而表达的第二部分总是会返回一个Type代表类型的对象Type ,不管是什么X是。 您想将typeof(int)typeof(int?) ,这是不同的。

我认为,表达式树的问题在于member变量是int类型而不是int?类型的Expression int? 您发布的代码未显示其来源,但我认为以下内容对您有帮助:

return Expression.Call(Expression.Constant(ids), method, Expression.Convert(member, typeof(int?)));

搜索答案并尝试此处的所有内容后,发现了这一点。

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

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

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM