C#无法将方法转换为非委托类型

我有一个名为Pin的课程。

 public class Pin { private string title; public Pin() { } public setTitle(string title) { this.title = title; } public String getTitle() { return title; } } 

从另一个类我在List引脚中添加Pins对象,从另一个类中我想迭代List引脚并获取元素。 所以我有这个代码。

 foreach (Pin obj in ClassListPin.pins) { string t = obj.getTitle; } 

使用此代码,我无法检索标题。 为什么?

(注意: ClassListPin只是一个包含一些元素的静态类,其中一个是List引脚)

您需要在方法调用后添加括号,否则编译器会认为您正在讨论方法本身(委托类型),而您实际上是在谈论该方法的返回值。

 string t = obj.getTitle(); 

额外的非必要信息

另外,看看属性。 这样你就可以使用title作为变量,而在内部,它就像一个函数。 这样你就不必编写函数getTitle()setTitle(string value) ,但你可以这样做:

 public string Title // Note: public fields, methods and properties use PascalCasing { get // This replaces your getTitle method { return _title; // Where _title is a field somewhere } set // And this replaces your setTitle method { _title = value; // value behaves like a method parameter } } 

或者您可以使用自动实现的属性,默认情况下将使用此属性:

 public string Title { get; set; } 

而且您不必创建自己的支持字段( _title ),编译器会自己创建它。

此外,您可以更改属性访问者(getter和setter)的访问级别:

 public string Title { get; private set; } 

您使用属性就像它们是字段一样,即:

 this.Title = "Example"; string local = this.Title; 

getTitle是一个函数,所以你需要在它之后放()

 string t = obj.getTitle(); 

正如@Antonijn所说,你需要通过添加括号来执行 getTitle方法:

  string t = obj.getTitle(); 

但我想补充一点,你在C#中进行Java编程。 有一些属性的概念(get和set方法对),在这种情况下应该使用它们:

 public class Pin { private string _title; // you don't need to define empty constructor // public Pin() { } public string Title { get { return _title; } set { _title = value; } } } 

更重要的是,在这种情况下,您不仅可以向编译器询问get和set方法的生成,还可以通过auto-inslemented属性使用来生成后端存储:

 public class Pin { public string Title { get; set; } } 

现在你不需要执行方法,因为像字段一样使用了属性:

 foreach (Pin obj in ClassListPin.pins) { string t = obj.Title; } 

如前所述,你需要使用obj.getTile()

但是,在这种情况下,我认为您正在寻找使用房产 。

 public class Pin { private string title; public Pin() { } public setTitle(string title) { this.title = title; } public String Title { get { return title; } } } 

这将允许您使用

 foreach (Pin obj in ClassListPin.pins) { string t = obj.Title; } 

您可以将类代码简化为以下内容,它将按原样运行,但如果您想使示例正常工作,请在末尾添加括号:string x = getTitle();

 public class Pin { public string Title { get; set;} } 

因为getTitle不是string ,所以如果您没有显式调用该方法,它会向方法(如果您愿意)返回引用或delegate

以这种方式调用您的方法:

 string t= obj.getTitle() ; //obj.getTitle() says return the title string object 

但是,这可行:

 Func method = obj.getTitle; // this compiles to a delegate and points to the method string s = method();//call the delegate or using this syntax `method.Invoke();` 

要执行一个方法,您需要添加括号,即使该方法不接受参数。

所以它应该是:

 string t = obj.getTitle();