泛型方法特性
- 僅支援方法宣告層級的型別參數
- 不支援屬性/事件/索引器等其他成員直接使用型別參數(但可使用外層泛型類別的參數)
- 可存在於泛型或非泛型類別中
完整範例
using System;
using System.Collections.Generic;
using System.Text;
namespace GenericTest
{
class GenericClass
{
// 宣告泛型方法
public T getvalue(T t) => t;
// 呼叫泛型方法:明確指定型別引數
public int useMethod() => this.getvalue(10);
// 多載:非泛型版本
public int getvalue(int i) => i;
}
// 覆寫示範:約束自動繼承,不需重複指定
abstract class Parent
{
public abstract K TEST(K k, V v) where K : V;
}
class Child : Parent
{
public override T TEST(T t, S s) => t;
}
}
關鍵點
- 呼叫時需明確指定型別引數:
getvalue(10)
- 多載解析優先匹配非泛型版本
- 覆寫時約束自動繼承,子類別無需重寫
where 子句