【问题标题】:Please explain the part of this delegate syntax: "<T>"请解释这个委托语法的一部分:“<T>”
【发布时间】:2014-12-04 16:10:27
【问题描述】:

几周前我问了一个相关问题,但没有解决这个特定的细节。

在这个委托中:

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

我知道第一个 T 是用户声明的返回对象,整个委托处理一个采用 SqlDataReader 的方法,但 &lt;T&gt; 是什么意思?

【问题讨论】:

  • 如果我没记错的话,T 在这种情况下是模板(或者基本上它可以用于几种类型之一)。
  • 表示委托人是generic。您可以使用任何类型来代替它:MyObject obj = LoadObject&lt;MyObject&gt;(myDataReader);。更多:msdn.microsoft.com/en-us/library/512aeb7t.aspx

标签: c# generics delegates


【解决方案1】:

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

为了消除您的疑虑,您可以仅将委托与那些与初始化委托引用具有相同类型的方法绑定:

例子-

        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;
        }

【讨论】:

    【解决方案2】:

    在 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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-19
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多