What's the point of “As” keyword in C#

后端 未结 7 1213
误落风尘
误落风尘 2020-12-13 01:32

From the docs:

The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. More formally, an exp

7条回答
  •  鱼传尺愫
    2020-12-13 02:02

    Let me give you real world scenarios of where you would use both.

    public class Foo
    {
      private int m_Member;
    
      public override bool Equals(object obj)
      {
        // We use 'as' because we are not certain of the type.
        var that = obj as Foo;
        if (that != null)
        {
          return this.m_Member == that.m_Member;
        }
        return false;   
      }
    }
    

    And...

    public class Program
    {
      public static void Main()
      {
        var form = new Form();
        form.Load += Form_Load;
        Application.Run(form);
      }
    
      private static void Form_Load(object sender, EventArgs args)
      {
        // We use an explicit cast here because we are certain of the type
        // and we want an exception to be thrown if someone attempts to use
        // this method in context where sender is not a Form.
        var form = (Form)sender;
    
      }
    }
    

提交回复
热议问题