我收到以下错误:"Using generic type 'Func<TResult>' requires 1 type arguments". It occurs when I attempt to define a dictionary which maps strings to delegate functions.
字典如下:
Dictionary<string, string> builtInFunctions = new Dictionary<string, Func<Expression, Dictionary<string, string>, Dictionary<string, Value>, Dictionary<string, Token>, Dictionary<string, Cube>, Result>>()
{
{"ToString", ToString}
};
Result ToString(
Expression expression,
Dictionary<string, string> env,
Dictionary<string, Value> store,
ref Dictionary<string, Token> tokenEnv,
ref Dictionary<string, Cube> cubeEnv
) {
// implemented ToString function
}
在此部分代码上发生了错误:
Func<Expression, Dictionary<string, string>, Dictionary<string, Value>, Dictionary<string, Token>, Dictionary<string, Cube>, Result>
例如,如果我使用其他更简单的类型,它仍然会出现:
Func<int, int, int, int, int, int>
委托函数只能接受4个参数,还是可以解决这个问题?
答案 0 :(得分:0)
您的ToString
函数不能具有ref
参数。
您的Func
中没有定义它们,也不能。
查看this question以获得更多见识。
您的代码可能有错误,因为声明带有四个或五个参数的Func
应该不成问题。
此代码对我来说效果很好:
using System;
using System.Collections.Generic;
public class Expression{}
public class Value{}
public class Token{}
public class Cube{}
public class Result{
public int result = 11;
}
namespace MyNameSpace{
using MyGenericFunc = Func<Expression, Dictionary<string, string>, Dictionary<string, Value>, Dictionary<string, Token>, Dictionary<string, Cube>, Result>;
public class Program
{
public static void Main()
{
Expression expression = new Expression();
Dictionary<string, string> env = new Dictionary<string, string>();
Dictionary<string, Value> store = new Dictionary<string, Value>();
Dictionary<string, Token> tokenEnv = new Dictionary<string, Token>();
Dictionary<string, Cube> cubeEnv = new Dictionary<string, Cube>();
// normal call
Console.WriteLine("When calling the method directly: " + ToStringFunc(expression, env, store, tokenEnv, cubeEnv).result);
// call via func and dictionary
MyGenericFunc retrievedFunc;
builtInFunctions.TryGetValue("ToString", out retrievedFunc);
Console.WriteLine("When calling the method retrieved from dictionary: " + retrievedFunc.Invoke(expression, env, store, tokenEnv, cubeEnv).result);
}
static Dictionary<string, MyGenericFunc> builtInFunctions = new Dictionary<string, MyGenericFunc>()
{
{"ToString", ToStringFunc}
};
static Result ToStringFunc(
Expression expression,
Dictionary<string, string> env,
Dictionary<string, Value> store,
Dictionary<string, Token> tokenEnv,
Dictionary<string, Cube> cubeEnv
) {
return new Result();
}
}
}
您可以here对其进行快速测试。