我有一个类叫做 Pin
.
public class Pin
{
private string title;
public Pin() { }
public setTitle(string title) {
this.title = title;
}
public String getTitle()
{
return title;
}
}
在另一个类中,我在 List<Pin>
中添加 Pins 对象引脚和另一个我想迭代列表引脚并获取元素。所以我有这段代码。
foreach (Pin obj in ClassListPin.pins)
{
string t = obj.getTitle;
}
使用此代码我无法检索标题。为什么?
(注意:ClassListPin
只是一个包含一些元素的静态类,其中之一是 List<Pin>
引脚)
最佳答案
您需要在方法调用后添加括号,否则编译器会认为您在谈论方法本身(委托(delegate)类型),而实际上您在谈论该方法的返回值。
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;
关于C# 无法将方法转换为非委托(delegate)类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14877355/