开发者

Check type of object where object may be an int (32 or 64)

I wou开发者_如何学Cld like to assign the property MyProperty with the parameter id.

The MyProperty property is of type Object, and it may be either an Int32 or an Int64.

How could I check the type of the MyProperty field and then assign it either id or id cast as an int depending on the underlying type?

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


So you want to assign the new value based on the type of the current value? If so:

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

You can do this with a conditional expression, but it's a bit ugly:

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

Or:

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

Or to make it clear that you really, really want boxing in either case:

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


You can do:

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

Is Operator.


As the others said, but I Recommend you use Convert instead of casting:

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


This question does not make sense. 1. If the property is an object you can assign whatever you want. The type of an object property is object. 2. If you want to see the underlying private field... how do you know there is an underlying field to begin with? If you do know there is a private field why don't you know its type?

If you are in the very strange second case you may do 2 things. a) Implement code in the property to do the check and conversion. b) Decorate the property with attributes that contain metadata about the underlying field and read it via reflection.

Overall your question indicates design problem so you'd best consider redesigning instead of hacking.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜