C#无法将方法转换为非委托类型 [英] C# cannot convert method to non delegate type
问题描述
我有一个叫做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<Pin>
引脚)
(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.
此外,您可以更改属性访问器(获取器和设置器)的访问级别:
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屋!