zoukankan      html  css  js  c++  java
  • .NET 泛型方法

     

    • 泛型方法
         泛型方法是使用类型参数声明的方法。
    static void Swap<T>(ref T lhs, ref T rhs)
    {
        T temp;
        temp = lhs;
        lhs = rhs;
        rhs = temp;
    }
    
    • 类型推断
         相同的类型推断规则也适用于静态方法以及实例方法。编译器能够根据传入的方法参数推断类型参数;它无法仅从约束或返回值推断类型参数。因此,类型推断不适用于没有参数的方法。类型推断在编译时、编译器尝试解析任何重载方法签名之前进行。编译器向共享相同名称的所有泛型方法应用类型推断逻辑。在重载解析步骤中,编译器仅包括类型推断取得成功的那些泛型方法。
    Swap(ref a, ref b);
    
    • 非泛型方法使用泛型参数
         在泛型类中,非泛型方法可以访问类级别类型参数。
    class SampleClass<T>
    {
        void Swap(ref T lhs, ref T rhs) { }
    }
    
    • 泛型类与泛型方法使用相同的泛型参数
         如果定义的泛型方法接受与包含类相同的类型参数,编译器将生成警告 CS0693,因为在方法范围内,为内部 T 提供的参数将隐藏为外部 T 提供的参数。除了类初始化时提供的类型参数之外,如果需要灵活调用具有类型参数的泛型类方法,请考虑为方法的类型参数提供其他标识符,如下面示例中的 GenericList2<T> 所示。
    class GenericList<T>
    {
        // CS0693
        void SampleMethod<T>() { }
    }
    class GenericList2<T>
    {
        //No warning
        void SampleMethod<U>() { }
    }
    
    • 泛型约束
         使用约束对方法中的类型参数启用更专门的操作。此版本的 Swap<T> 现在称为 SwapIfGreater<T>,它只能与实现 IComparable<T> 的类型参数一起使用。
    void SwapIfGreater<T>(ref T lhs, ref T rhs) where T : System.IComparable<T>
    {
        T temp;
        if (lhs.CompareTo(rhs) > 0)
        {
            temp = lhs;
            lhs = rhs;
            rhs = temp;
        }
    }
    
    • 方法重载
         泛型方法可以使用许多类型参数进行重载。
    void DoWork() { }
    void DoWork<T>() { }
    void DoWork<T, U>() { }
    
  • 相关阅读:
    numpy 基础 —— np.linalg
    图像旋转后显示不完全
    opencv ---getRotationMatrix2D函数
    PS1--cannot be loaded because the execution of scripts is disabled on this system
    打开jnlp Faild to validate certificate, the application will not be executed.
    BATCH(BAT批处理命令语法)
    oracle vm virtualbox 如何让虚拟机可以上网
    merge 实现
    Windows batch,echo到文件不成功,只打印出ECHO is on.
    python2.7.6 , setuptools pip install, 报错:UnicodeDecodeError:'ascii' codec can't decode byte
  • 原文地址:https://www.cnblogs.com/liusuqi/p/3123186.html
Copyright © 2011-2022 走看看