当Tinput,Toutput是通用的时,无法使用委托函数分配C# - Func <tinput1,tinput2,toutput>

时间:2015-12-26 05:22:24

标签: c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

           function4<int, double, string>();

        }

        public static string function1(int i, double d)
        {

            return "return_string";
        }

        public static void function4<D1,D2,D3>()
        {
           // Func<D1, D2, D3> f1 = function1; //does not work? Any idea why?
            Func<int, double,string> f1 = function1; //works fine
            string s = f1(10, 20);

        }

    }
}

为什么无法将function1指定为Func<D1, D2, D3> f1 = function1? 但是Func<int,double,string> f1 = function1时它可以正常工作。 我试图使参数更加通用。

1 个答案:

答案 0 :(得分:1)

function4上的泛型参数的要点是您可以使用不同的参数类型调用它,例如:

function4<string, string, string>();
function4<int, char, string>();

但显然,function1的方法签名与上述示例不兼容。编译器不能假设function4只会以这种方式调用:function4<int, double, string>();,因此它会为您提供一个错误,以防止您使用不同的参数类型进行其他可能的调用。

如果您只想使用function4作为通用参数类型调用<int, double, string>,那么您首先根本不需要泛型。