检查对象的类型,对象可以是int(32或64)

时间:2010-07-07 19:24:31

标签: c# casting types

我想使用参数 id 指定属性 MyProperty

MyProperty属性的类型为Object,它可以是Int32或Int64。

我如何检查MyProperty字段的类型,然后根据底层类型将id或id转换为int?

public void MyMethod(long id) {
    myClass.MyProperty
        = (typeof(MyProperty) == typeof(long))
        ? id
        : (int)id;
}

4 个答案:

答案 0 :(得分:2)

你可以这样做:

if(myClass.MyProperty is int){
.....  do int stuff
}
else
{
 ..... do long stuff.
}

Is Operator.

答案 1 :(得分:2)

所以你想根据当前值的类型分配新值?如果是这样的话:

if (myClass.MyProperty is int)
{
    myClass.MyProperty = (int) id;
}
else
{
    myClass.MyProperty = id;
}

可以使用条件表达式执行此操作,但它有点难看:

myClass.MyProperty = myClass.MyProperty is int 
    ? (object) id : (int) id;

或者:

myClass.MyProperty = myClass.MyProperty is int 
    ? (object) (int) id : id;

或者要明确表示你真的非常想要拳击:

myClass.MyProperty = myClass.MyProperty is int 
    ? (object) (int) id : (object) id;

答案 2 :(得分:1)

正如其他人所说,但我建议您使用转换而不是转换:

long l = 2147483648; // int.MaxValue + 1
int i = (int)l; // i == -2147483648 oops
i = Convert.ToInt32(l); // Overflow exception

答案 3 :(得分:0)

这个问题没有意义。 1.如果属性是对象,则可以分配任何所需内容。对象属性的类型是object。 2.如果你想看到潜在的私人领域......你怎么知道有一个潜在的领域开始?如果您确实知道有私人领域,为什么不知道它的类型?

如果你处于非常奇怪的第二种情况,你可以做两件事。 a)在属性中实现代码以进行检查和转换。 b)使用包含有关基础字段的元数据的属性装饰属性,并通过反射读取它。

总体而言,您的问题表明设计问题,因此您最好考虑重新设计而不是黑客攻击。