【发布时间】:2015-11-17 05:34:21
【问题描述】:
使用表达式主体成员允许您将方法或属性的主体定义为没有 return 关键字的单个表达式(它是否应该返回某些内容)。
比如它转这些
int Method1()
{
return 5;
}
void Method2()
{
Console.WriteLine();
}
进入这些
int Method1() => 5;
void Method2() => Console.WriteLine();
当您从主体中抛出异常时,差异就会发挥作用:
void Method3()
{
throw new Exception();
}
但是,以下内容不会编译:
void Method3() => throw new Exception();
带有以下消息:
Warning The member 'Program.Exception()' does not hide an inherited member. The new keyword is not required.
Error 'Program.Exception()' must declare a body because it is not marked abstract, extern, or partial
Error ; expected
Error Invalid token 'throw' in class, struct, or interface member declaration
Error Method must have a return type
Error Invalid expression term 'throw'
为什么?
【问题讨论】:
-
不错。然而,只抛出异常的方法是异常抛出器!而且没有用,因为你可以直接抛出异常:)
-
@M.kazemAkhgary:我预计这是在尚未实现的方法中的常见情况,显然,抛出
NotImplementedException