Why can't an anonymous method be assigned to v

2020-01-24 02:00发布

I have the following code:

Func<string, bool> comparer = delegate(string value) {
    return value != "0";
};

However, the following does not compile:

var comparer = delegate(string value) {
    return value != "0";
};

Why can't the compiler figure out it is a Func<string, bool>? It takes one string parameter, and returns a boolean. Instead, it gives me the error:

Cannot assign anonymous method to an implicitly-typed local variable.

I have one guess and that is if the var version compiled, it would lack consistency if I had the following:

var comparer = delegate(string arg1, string arg2, string arg3, string arg4, string arg5) {
    return false;
};

The above wouldn't make sense since Func<> allows only up to 4 arguments (in .NET 3.5, which is what I am using). Perhaps someone could clarify the problem. Thanks.

7条回答
Rolldiameter
2楼-- · 2020-01-24 02:43

How is about that?

var item = new
    {
        toolisn = 100,
        LangId = "ENG",
        toolPath = (Func<int, string, string>) delegate(int toolisn, string LangId)
        {
              var path = "/Content/Tool_" + toolisn + "_" + LangId + "/story.html";
              return File.Exists(Server.MapPath(path)) ? "<a style=\"vertical-align:super\" href=\"" + path + "\" target=\"_blank\">execute example</a> " : "";
        }
};

string result = item.toolPath(item.toolisn, item.LangId);
查看更多
登录 后发表回答