40

我有一堂课叫Pin.

public class Pin
{
    private string title;

    public Pin() { }

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

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

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

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

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

4

7 回答 7

68

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

string t = obj.getTitle();

额外的非必要信息

另外,看看属性。这样你就可以像使用变量一样使用title,而在内部,它就像一个函数一样工作。这样你就不必编写函数getTitle()and 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;
于 2013-02-14T14:47:00.933 回答
7

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

string t = obj.getTitle();
于 2013-02-14T14:47:30.480 回答
7

正如@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-impelemented 属性使用来生成反向存储:

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

现在您不需要执行方法,因为使用的属性类似于字段:

foreach (Pin obj in ClassListPin.pins)
{
     string t = obj.Title;
}
于 2013-02-14T14:51:40.643 回答
5

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

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

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;
}
于 2013-02-14T14:51:20.407 回答
5

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

public class Pin
{
   public string Title { get; set;}
}
于 2013-02-14T14:53:48.627 回答
3

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

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

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

但是,这会起作用:

Func<string> 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();`
于 2013-02-14T14:46:59.187 回答
2

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

所以应该是:

string t = obj.getTitle();
于 2013-02-14T14:47:30.520 回答