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

前端 未结 5 1187
无人及你
无人及你 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:45

    This feature is coming in C#7. From https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/

    It is easy to throw an exception in the middle of an expression: just call a method that does it for you! But in C# 7.0 we are directly allowing throw as an expression in certain places:

    class Person
    {
        public string Name { get; }
        public Person(string name) => Name = name ?? throw new ArgumentNullException(name);
        public string GetFirstName()
        {
            var parts = Name.Split(" ");
            return (parts.Length > 0) ? parts[0] : throw new InvalidOperationException("No name!");
        }
        public string GetLastName() => throw new NotImplementedException();
    }
    

    Edit:

    Updating this question to add links to newer info around how throw can now be used as an expression in expression-bodied members, ternary expressions and null-coalescing expressions, now that C# 7 is released:

    What's new in C# 7 - Throw expressions.

    New Features in C# 7.0.

提交回复
热议问题