Direct casting vs 'as' operator?

后端 未结 16 1824
独厮守ぢ
独厮守ぢ 2020-11-22 01:43

Consider the following code:

void Handler(object o, EventArgs e)
{
   // I swear o is a string
   string s = (string)o; // 1
   //-OR-
   string s = o as str         


        
16条回答
  •  名媛妹妹
    2020-11-22 02:01

    "(string)o" will result in an InvalidCastException as there's no direct cast.

    "o as string" will result in s being a null reference, rather than an exception being thrown.

    "o.ToString()" isn't a cast of any sort per-se, it's a method that's implemented by object, and thus in one way or another, by every class in .net that "does something" with the instance of the class it's called on and returns a string.

    Don't forget that for converting to string, there's also Convert.ToString(someType instanceOfThatType) where someType is one of a set of types, essentially the frameworks base types.

提交回复
热议问题