[英]why a non generic derived type must specify the type parameter for a generic base class C#
[英]C# Specify generic type parameter once and use it throughout class
假設我有一個ClassWhichDoesThings
類,它對方法進行各種調用,例如
DoSomething<TheTypeIWantToSpecifyOnce>();
DoAnotherThing<TheTypeIWantToSpecifyOnce>();
AndAnother<TheTypeIWantToSpecifyOnce>();
整個班級。
是否可以在一個地方指定泛型類型(如變量但不是在運行時確定),而類之外的任何東西都必須傳遞泛型類型(避免ClassWhichDoesThings<T>
),這樣方法調用就變成了這樣:
Type WriteTypeOnce = typeof(TheTypeIWantToSpecifyOnce);
DoSomething<WriteTypeOnce>();
DoAnotherThing<WriteTypeOnce>();
AndAnother<WriteTypeOnce>();
這里的目標是,如果我想更改類型,例如,我不必對 20 個不同的方法調用進行查找和替換。
本質上,我想要一個泛型類,它私下指定自己的泛型類型。
編輯:換句話說,我試圖更好地組織對類完全私有但專注於處理單個類型的代碼。 例如,假設我想添加方法:
public TheTypeIWantToSpecifyOnce CreateAThing(string input){ ... }
我希望非常清楚,這個類專注於TheTypeIWantToSpecifyOnce
或T
以便使用T
編寫另一個方法很容易,但在創建類時沒有指定T
...
根據情況,您可以創建內部泛型方法或類並使用它,使類本身基本上是一個包裝器:
public class SomeClass
{
private readonly int Data = 1;
private Generic<ActualType> Instance;
public SomeClass()
{
Instance = new(this);
}
public int SomeMethod => Instance.SomeMethodImpl();
public int SomeMethod1 => Instance.SomeMethodImpl2();
private class Generic<TheTypeIWantToSpecifyOnce>
{
private readonly SomeClass _instance;
// if needed - pass the parent class instance to reference it's internal data
// if not - remove both ctors and
// just init with Generic<ActualType> Instance = new();
public Generic(SomeClass instance)
{
_instance = instance;
}
public int SomeMethodImpl() => DoSomething<TheTypeIWantToSpecifyOnce>();
public int SomeMethodImpl2()
{
Console.WriteLine(_instance.Data); // use parent internal data if needed
DoAnotherThing<TheTypeIWantToSpecifyOnce>();
return AndAnother<TheTypeIWantToSpecifyOnce>();
}
}
}
另一種方法可以使用別名指令:
using TheTypeIWantToSpecifyOnce = System.Int32;
public class SomeClass
{
public int SomeMethod => DoSomething<TheTypeIWantToSpecifyOnce>();
public int SomeMethod1()
{
DoAnotherThing<TheTypeIWantToSpecifyOnce>();
return AndAnother<TheTypeIWantToSpecifyOnce>();
}
}
是的,您可以編寫帶有類型參數的方法
static void DoAllThings<T>()
{
DoSomething<T>();
DoAnotherThing<T>();
AndAnother<T>();
}
並調用它
DoAllThings<TheTypeIWantToSpecifyOnce>();
另請注意, T
是在方法上指定的,而不是在類上指定的,並且僅在類內部是已知的。
這也可以是局部函數,即方法內的函數。
但要明確:泛型不是動態的,即,您不能使用運行時類型(作為System.Type
類型的變量或參數給出)作為泛型類型參數的參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.