Why can't I throw exceptions from an expression-bodied member?

前端 未结 5 1209
无人及你
无人及你 2021-01-07 16:51

Using expression-bodied members allows you to define the body of a method or property as a single expression without a return keyword (should it return something).

F

5条回答
  •  自闭症患者
    2021-01-07 17:35

    Although its a old thread, but C# now supports throw expressions which were added in C# 7.

    Previously,

    var colorString = "green,red,blue".Split(',');
    var colors = (colorString.Length > 0) ? colorString : null
    if(colors == null){throw new Exception("There are no colors");}
    

    No more. Now, as Null coalescing operator:

    var firstName = name ?? throw new ArgumentException ();
    

    As Conditional Operator:

    It is also possible in the Conditional Operator as well.

    var arrayFirstValue = (array.Length > 0)? array[1] : 
      throw new Expection("array contains no elements");
    

    Expression bodied member:

    public string GetPhoneNumber () => throw new NotImplementedException();
    

提交回复
热议问题