在C#中,nameof
關鍵字用于獲取一個類型的名稱或一個表達式的名稱。然而,nameof
不能直接處理泛型類型,因為它需要一個具體的類型或者一個具體的表達式。但是,你可以使用一些技巧來處理泛型類型。
假設你有一個泛型類MyGenericClass<T>
,并且你想要獲取這個泛型類型的名稱。你可以通過創建一個非泛型的包裝類來實現這個目標:
public class MyGenericClass<T>
{
// ...
}
public static class MyGenericClassExtensions
{
public static string GetGenericTypeName<T>(this T instance)
{
return typeof(MyGenericClass<>).GetGenericTypeDefinition().Name;
}
}
現在,你可以使用GetGenericTypeName
方法來獲取泛型類型的名稱:
var myInstance = new MyGenericClass<int>();
string typeName = myInstance.GetGenericTypeName(); // 輸出 "MyGenericClass`1"
請注意,這個方法返回的名稱包含了泛型參數的數量和值(例如,MyGenericClass
1)。如果你只想要泛型參數的數量,你可以使用以下方法:
public static string GetGenericTypeNameWithoutParameters<T>(this T instance)
{
return typeof(MyGenericClass<>).GetGenericTypeDefinition().Name.Remove(typeof(MyGenericClass<>).GetGenericTypeDefinition().Name.IndexOf('`'));
}
這個方法將返回不包含泛型參數值的名字(例如,MyGenericClass
)。