![](/img/trans.png)
[英]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.