我正在学习c#委托。在编译这段代码时,我在主题行中收到了这个错误信息。
不能隐式地将类型'int'转换为' foo . bar . delegate . 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());
}
}
}
所以我被困住了,直到我能理解我做错了什么。如果有人能帮我解决这个问题,我会非常感激。
首先,你的委托类型应该是:
private delegate int ParseIntDelegate(string str);
委托类型应与要转换的方法的签名匹配。在本例中,Parse
接受单个string
参数并返回int
。
因为你的Parse
方法有一个兼容的签名,你可以直接从它创建一个新的委托实例:
ParseIntDelegate firstParseIntMethod = Parse;
然后你可以像一个普通的方法应用程序那样调用它:
Console.WriteLine("Integer is {0}", firstParseIntMethod(x));
有几件事引起了我的注意:
在Main()中有
ParseIntDelegate firstParseIntMethod = Parse(x);
尝试将Parse(x)的结果存储到firstParseIntMethod中。你在这里调用了 Parse,而不是引用它。
你可以通过删除参数来解决这个问题:
ParseIntDelegate firstParseIntMethod = Parse ;
现在你会有一个不同的错误,抱怨Parse的签名。
private delegate int ParseIntDelegate();
private static int Parse(string x)
Parse不能'fit' into ParseIntDelegate,因为它需要一个字符串参数。你可以改变ParseIntDelegate让它接受一个字符串来解决这个问题。