Getting an int value out of an object
When I use the following code it feels like I'm going wrong somewhere.
object obj = 1;
int i = int.Par开发者_JS百科se(obj.ToString());
Is there a simpler way?
Well, what is actually in the obj
? If it is just a boxed int
, then simply cast to unbox:
int i = (int)obj;
For less predetermined content you might also try:
int i = Convert.ToInt32(obj);
which will handle a number of scenarios and doesn't add an extra string
in the mix.
Try this instead:
object obj = 1;
// Option 1: Convert. This will work when obj contains anything
// convertible to int, such as short, long, string, etc.
int i = Convert.ToInt32(obj);
// Option 2: Cast. This will work only when obj contains an int,
// and will fail if it contains anything else, like a long.
int i = (int)obj;
You should cast:
object obj = 1;
int i = (int) obj;
This is called static cast.
For your information, there is another cast called dynamic cast which can only work with reference types (types that can have the null value), so not in this case (int is a value type):
object obj = DateTime.Now;
DateTime date = obj as DateTime;
The difference between the two methods is that if the casted object doesn't have the required type, it will raise an exception in the first case (static cast), and it will return null in the second case (dynamic cast).
精彩评论