C#无法将方法转换为非委托类型
我有一个叫做C#无法将方法转换为非委托类型,c#,.net,methods,delegates,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; } } 从另一个类中,我在列表中添加Pins对象,从另一个类中,我想迭代列表
Pin
的类
public class Pin
{
private string title;
public Pin() { }
public setTitle(string title) {
this.title = title;
}
public String getTitle()
{
return title;
}
}
从另一个类中,我在列表中添加Pins对象,从另一个类中,我想迭代列表Pins并获取元素。所以我有这个代码
foreach (Pin obj in ClassListPin.pins)
{
string t = obj.getTitle;
}
使用此代码,我无法检索标题。为什么?
(注意:ClassListPin
只是一个包含一些元素的静态类,其中一个元素是List
pins)因为getTitle
不是字符串,如果您不显式调用该方法,它将返回对该方法的引用或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();`
Func method=obj.getTitle;//这将编译为委托并指向该方法
字符串s=方法()//调用委托或使用以下语法`method.Invoke()`
您需要在方法调用后添加括号,否则编译器会认为您在谈论方法本身(委托类型),而实际上您在谈论该方法的返回值
string t = obj.getTitle();
额外的非必要信息
另外,请查看属性。这样,您可以像使用变量一样使用title,而在内部,它的工作方式类似于函数。这样,您就不必编写函数getTitle()
和setTitle(字符串值)
,但您可以这样做:
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; }
您不必创建自己的支持字段(\u title
),编译器将自己创建它
此外,还可以更改属性访问器(getter和setter)的访问级别:
将属性当作字段使用,即:
this.Title = "Example";
string local = this.Title;
要执行方法,您需要添加括号,即使该方法不带参数
因此,它应该是:
string t = obj.getTitle();
getTitle
是一个函数,因此需要在它后面加上()
string t = obj.getTitle();
如前所述,您需要使用obj.getTile()
但是,在这种情况下,我认为您正在寻求使用一种新的方法
这将允许您使用
foreach (Pin obj in ClassListPin.pins)
{
string t = obj.Title;
}
正如@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方法,还可以通过用法要求编译器生成后台存储:
现在您不需要执行方法,因为属性与字段类似:
foreach (Pin obj in ClassListPin.pins)
{
string t = obj.Title;
}
您可以将您的类代码简化为下面的代码,它将按原样工作,但是如果您想让示例工作,请在末尾添加括号:string x=getTitle()
因为你需要调用它,例如obj.getTitle()
你试过搜索谷歌吗?这是一个相当常见的初学者错误。有点离题,但引入属性是为了反对编写setter和getter。更多信息:我承认这是一个愚蠢的错误…哦,我的上帝。。。这是一个幼稚的错误!它应该是Title
,而不是getTitle
。
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; }
}
}
public class Pin
{
public string Title { get; set; }
}
foreach (Pin obj in ClassListPin.pins)
{
string t = obj.Title;
}
public class Pin
{
public string Title { get; set;}
}