Direct casting vs 'as' operator?

后端 未结 16 1822
独厮守ぢ
独厮守ぢ 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:10

    I would like to attract attention to the following specifics of the as operator:

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/as

    Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

提交回复
热议问题