C# 无法将方法转换为非委托类型 [英] C# cannot convert method to non delegate type
问题描述
我有一个名为 Pin
的类.
I have a class called Pin
.
public class Pin
{
private string title;
public Pin() { }
public setTitle(string title) {
this.title = title;
}
public String getTitle()
{
return title;
}
}
从另一个类中,我在 List<Pin>
引脚中添加 Pins 对象,并且从另一个类中我想迭代 List 引脚并获取元素.所以我有这个代码.
From another class I add Pins objects in a List<Pin>
pins and from another I want to iterate the List pins and get the elements. So I have this code.
foreach (Pin obj in ClassListPin.pins)
{
string t = obj.getTitle;
}
使用此代码我无法检索标题.为什么?
With this code I cannot retrieve the title. Why?
(注意:ClassListPin
只是一个包含一些元素的静态类,其中一个是List
引脚)
(Note: ClassListPin
is just a static class which contains some elements and one of these, is the List<Pin>
pins)
推荐答案
你需要在方法调用后添加括号,否则编译器会认为你在谈论方法本身(委托类型),而你是实际上是在谈论那个方法的返回值.
You need to add parentheses after a method call, else the compiler will think you're talking about the method itself (a delegate type), whereas you're actually talking about the return value of that method.
string t = obj.getTitle();
<小时>
额外的非必要信息
另外,看看属性.这样你就可以把 title 当作一个变量来使用,而在内部,它就像一个函数.这样你就不必编写函数 getTitle()
和 setTitle(string value)
,但你可以这样做:
Also, have a look at properties. That way you could use title as if it were a variable, while, internally, it works like a function. That way you don't have to write the functions getTitle()
and setTitle(string value)
, but you could do it like this:
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
}
}
或者您可以使用自动实现的属性,默认情况下会使用它:
Or you could use auto-implemented properties, which would use this by default:
public string Title { get; set; }
而且您不必创建自己的支持字段 (_title
),编译器会自行创建.
And you wouldn't have to create your own backing field (_title
), the compiler would create it itself.
此外,您可以更改属性访问器(getter 和 setter)的访问级别:
Also, you can change access levels for property accessors (getters and setters):
public string Title { get; private set; }
您可以像使用字段一样使用属性,即:
You use properties as if they were fields, i.e.:
this.Title = "Example";
string local = this.Title;
这篇关于C# 无法将方法转换为非委托类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!