我正在努力学习C#代表。在编译这段代码时,我会在主题行中收到此错误消息。
不能隐式地将类型'int‘转换为'Foo.Bar.Delegates.Program.ParseIntDelegate’
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Foo.Bar.Delegates
{
class Program
{
private delegate int ParseIntDelegate();
private static int Parse(string x)
{
return int.Parse(x);
}
static void Main()
{
string x = "40";
int y = Parse(x); //The method I want to point the delegate to
ParseIntDelegate firstParseIntMethod = Parse(x);
//generates complier error: cannot implicity convert type int
//to 'Foo.Bar.Delegates.Program.ParseIntDelegate'
ParseIntDelegate secondParseIntMethod = int.Parse(x); //Same error
Console.WriteLine("Integer is {0}", firstParseIntMethod());
}
}
}所以我被困住了,直到我能理解我做错了什么。如果有人能帮我解决这个问题,我会非常感激的。
发布于 2013-03-28 21:10:55
首先,您的委托类型应该是:
private delegate int ParseIntDelegate(string str);委托类型应该与要转换的方法的签名相匹配。在本例中,Parse接受一个string参数并返回一个int。
由于Parse方法具有兼容的签名,因此可以直接从它创建一个新的委托实例:
ParseIntDelegate firstParseIntMethod = Parse;然后,您可以像普通的方法应用程序一样调用它:
Console.WriteLine("Integer is {0}", firstParseIntMethod(x));发布于 2013-03-28 21:18:10
有几件事让我大吃一惊:
在Main()中,您已经
ParseIntDelegate firstParseIntMethod = Parse(x);这将尝试将Parse(x)的结果存储到firstParseIntMethod中。你在这里引用Parse,不是指它。
您可以通过移除参数来修复这个问题:
ParseIntDelegate firstParseIntMethod = Parse ; 现在,您将有一个不同的错误,抱怨Parse的签名。
private delegate int ParseIntDelegate();
private static int Parse(string x)因为ParseIntDelegate需要一个字符串参数,所以它不能“适合”。您可以更改ParseIntDelegate以获取一个字符串来解决问题。
https://stackoverflow.com/questions/15692175
复制相似问题