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

标签 c# .net methods delegates

我有一个类叫做 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/

相关文章:

javascript - 在 JavaScript 中引用和调用方法

c# - 如果实现在同一个程序集中,为什么部分方法不能公开?

.net - 我如何实际将 "dotnet try-convert"应用于要转换为 .net 核心的文件?

java - 是否可以使方法连续运行直到我输入特殊字符

c# - EF 一对一关系改变实体与另一个实体(替代)

c# - 磁盘上连续的内存映射文件

java - 如何使用方法在同一行中打印 "*"x 次?

c# - stream 不支持并发 IO 读写操作

c# - 使用 Html.Helper 函数创建多行文本框

c# - 如何从 C# 中的代码构建 HTML