C#6,表达式函数编译错误

时间:2018-04-11 09:02:25

标签: c# visual-studio-2015

我在VS 2015中使用Dot Net framework 4.6.1在我的班级编写以下代码。

public int NewWaySum(int a, int b) => return a + b;

但它引发了编译错误。这是我的班级:

public class MyClass {
    public int NewWaySum(int a, int b) => return a + b;
}

根据Msdn,它与C#6.0表达式身体兼容,并且应该编译。

到目前为止,我还没有使用过表达身体的功能。

错误是"无效的令牌'返回',在类,结构或接口成员声明中。

错误是什么。 VS 2017社区版中发生了相同的编译错误

2 个答案:

答案 0 :(得分:6)

表达式身体方法中,您不需要import sys def text(): countV = 0 countC = 0 lines = 0 countU = 0 countL = 0 characters = 0 vowels = set("AEIOUaeiou") cons = set("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ") upper = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ") lower = set("abcdefghijklmnopqrstuvwxyz") with open(sys.argv[1]) as file: fileLines = file.readlines() for line in fileLines: lines = lines + 1 characters = characters + len(line) for char in line: if char in vowels: countV = countV + 1 elif char in cons: countC = countC + 1 for char in line: if char in upper: countU = countU + 1 elif char in lower: countL = countL + 1 print("Lines: " + str(lines)) print("Characters: " + str(characters)) print("Vowels: " + str(countV)) print("Consonants: " + str(countC)) print("Lowercase: " + str(countL)) print("Uppercase: " + str(countU)) text() 。因为您只声明表达式,并且此表达式的值是返回的值:

return

答案 1 :(得分:1)

表达式主体不得包含return。所以

public int NewWaySum(int a, int b) => a + b;

将起作用