你好伙伴stackoverflow成员!
我是Java,Obj-C的C#语言转换的新手.它看起来和Java非常相似,但我在很简单的事情上遇到麻烦.我创建了两个单独的类文件,Class-A和Class-Human.
它包含声明的静态main方法.我尝试创建Class-Human的新实例.
public static void main(String args[])
{
Human human = new Human("Yoon Lee", 99);
int expected = human.getNetID; //<-gets the error at this moment.
}
Run Code Online (Sandbox Code Playgroud)
namespace Class-A
{
public class Human
{
public String name;
public int netId;
public Human(String name, int netId)
{
this.name = name;
this.netId = netId;
}
public int getNetID()
{
return netId;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么不能复制到局部变量?编译器提示我错误
'Cannot convert method group of 'getNetID' delegate blah blah'
Run Code Online (Sandbox Code Playgroud)
谢谢.
将方法调用更改为:
int expected = human.getNetID();
Run Code Online (Sandbox Code Playgroud)
在C#中,方法调用需要()包含以逗号分隔的参数列表的parantheses.在这种情况下,该getNetID方法是无参数的; 但是空的parantheses仍然需要表明你的意图是调用方法(而不是,例如,将method-group转换为delegate-type).
此外,正如其他人所指出的那样,方法的返回类型与您分配其值的变量之间存在不匹配,您将不得不以某种方式解决该变量(更改字段类型和方法) return-type to int/ parse the string as an integer,etc.).
另一方面,C#本身支持getter-setter语义的属性,因此写这个的惯用方法如下:
//hyphens are not valid in identifiers
namespace ClassA
{
public class Human
{
// these properties are publicly gettable but can only be set privately
public string Name { get; private set; }
public int NetId { get; private set; }
public Human(string name, int netId)
{
this.Name = name;
this.NetId = netId;
}
// unlike Java, the entry-point Main method begins with a capital 'M'
public static void Main(string[] args)
{
Human human = new Human("Yoon Lee", 99);
int expected = human.NetId; // parantheses not required for property-getter
}
}
}
Run Code Online (Sandbox Code Playgroud)