(int)value or value as int?

Possible Duplicate:
Direct casting vs 'as' operator?

Can someone explain the difference to me and which one is better to use? I know in some situations I can only use one or the other.

(int)value

value as int


The latter is invalid. You can use

value as int?

if you need to "convert if possible". That's slower than

if (value is int)
{
    int x = (int) value;
    ...
}

though. That's what you should probably use if you're not confident that value is actually an int . If, however, your code is such that if value isn't an int , that represents a bug, then just cast unconditionally:

int x = (int) value;

If that fails, it will throw an exception - which is generally appropriate for a bug.


I value as int will cause a compiler error because operator must be used with a reference type or nullable type ('int' is a non-nullable value type) . So when dealing with structs, you always use (int)value and with Objects, I prefer obj as SomeType because it is clearer and more straight to the point, plus it handles exceptions automatically (if an error occurs during casting the operator returns null).

链接地址: http://www.djcxy.com/p/73734.html

上一篇: 演员中的内容与众不同

下一篇: (int)值或值为int?