Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 请解释此委托语法的部分:“”_C#_Generics_Delegates - Fatal编程技术网

C# 请解释此委托语法的部分:“”

C# 请解释此委托语法的部分:“”,c#,generics,delegates,C#,Generics,Delegates,几周前我问了一个相关的问题,但这个具体细节没有得到解决 在此代表中: public delegate T LoadObject<T>(SqlDataReader dataReader); 我知道第一个T是用户声明的返回对象,整个委托处理一个接受SqlDataReader的方法,但这意味着什么 如果您熟悉Dot-Net泛型,那么使用泛型委托不应该是一个问题。 如@pwas所述,请参考MSDN通用文档 为了澄清您的疑问,您可以仅使用与初始化的委托引用类型相同的方法绑定委托: 范例-

几周前我问了一个相关的问题,但这个具体细节没有得到解决

在此代表中:

public delegate T LoadObject<T>(SqlDataReader dataReader);

我知道第一个T是用户声明的返回对象,整个委托处理一个接受SqlDataReader的方法,但这意味着什么

如果您熟悉Dot-Net泛型,那么使用泛型委托不应该是一个问题。 如@pwas所述,请参考MSDN通用文档

为了澄清您的疑问,您可以仅使用与初始化的委托引用类型相同的方法绑定委托:

范例-

        public delegate T LoadObject<T>(SqlDataReader dataReader);

        static void Main(string[] args)
        {
            LoadObject<int> del = Test1; //Valid
            LoadObject<string> del1 = Test1; //Compile Error
        }

        public static int Test1(SqlDataReader reader)
        {
            return 1;
        }

在C语言中,我们有泛型类、泛型方法、泛型委托、泛型接口和泛型结构。考虑下面的例子:

public delegate T MaxDelegate<T>(T a, T b);
void Main()
{

    Console.WriteLine(  MaxClass<int>.whatIsTheMax(2,3) );

    // Just as a class when using a generic method,You must tell the compiler
    // the type parameter
    Console.WriteLine( MaxMethod<int>(2,3) );

    // Now the max delegate of type MaxDelegate will only accept a method that has
    //   int someMethod(int a, int b) .It has the benefit of compile time check
    MaxDelegate<int>  m = MaxMethod<int>;

    // MaxDelegate<int> m2 = MaxMethod<float>; // compile time check and error



    m(2,3);
   //m(2.0,3.0);  //compile time check and error
}

public static T MaxMethod<T>(T a, T b) where T : IComparable<T>
{
   T retval = a;
   if(a.CompareTo(b) < 0)
     retval = b;
   return retval;
}

public class MaxClass<T> where T : IComparable<T>
{
    public static  T whatIsTheMax(T a, T b)
   {
       T retval = a;
        if ( a.CompareTo(b) < 0)
            retval = b;
        return retval;
    }
}

如果我没记错的话,在本例中T是模板,或者基本上它可以用于几种类型中的一种,这意味着委托是泛型的。您可以使用任何类型来代替它:MyObject obj=LoadObjectmyDataReader;。更多: