简体   繁体   English

通过从C#中的方法分配值来声明字符串时出错

[英]Error when declaring a String by assigning a value from a method in c#

I am learning C# in Unity but I am receiving a weird error. 我正在Unity中学习C#,但收到一个奇怪的错误。 Error is saying "Expression denotes a variable', where a method group' was expected" 错误是说“表达式表示variable', where a预期方法组”

This is the line that gives the error: 这是给出错误的行:

string walkingDir = walkingDir();

This is the walkingDir() method: 这是walkingDir()方法:

private string walkingDir(){
return "str";}

Replacing 更换

string walkingDir = walkingDir(); 

with

string walkingDir = "str";

works. 作品。

Your problem is that your variable and method have the same name. 您的问题是您的变量和方法具有相同的名称。 Change the name of your variable and it will compile. 更改变量的名称,它将进行编译。 Eg 例如

string walkDir = walkingDir(); 

You are getting that error because the name of the function is the-same as the name of the variable which are both "walkingDir" . 之所以会出现此错误,是因为函数的名称与变量的名称相同,都是“ walkingDir”

You have to either rename the function or the variable. 您必须重命名函数或变量。

string walkingDir = getWalkingDir();

and

private string getWalkingDir()
{
    return "str";
}

Another way to fix this without re-naming the variables is to use the this keyword to tell the compiler to use the local function name instead of the variable name. 无需重命名变量即可解决此问题的另一种方法是使用this关键字告诉编译器使用局部函数名而不是变量名。

This should work too: 这也应该工作:

string walkingDir = this.walkingDir();

and

private string walkingDir()
{
    return "str";
}

Even though that should work, I encourage you to prevent naming your variable or function name the-same. 即使这行得通,我还是鼓励您避免将变量或函数名称命名为相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM