获取映射到枚举的值时,如何调用正确的泛型方法
本文关键字:调用 何调用 泛型方法 映射 枚举 获取 | 更新日期: 2023-09-27 18:12:36
我正在从数据库中获取SomeThingType,然后想要呼叫SomeThing<T>(T value)
。我在运行时从数据库获取类型。
我被卡住了,我该怎么做?
ProductType productType = GetProductType(userId);
SomeThingType someThingType = GetSomeThingTypeFromDb(userId);
switch(productType)
{
case ProductType.ONE:
// stuck here
IThing<int> a = new SomeThing<int>(..);
IThing<string> a = new SomeThing<string>(..);
IThing<DateTime> a = new SomeThing<DateTime>(..);
break;
}
我被困在如何根据我在运行时从数据库检索的枚举值使用正确的泛型类型。
db值映射到一个枚举,我想用它来确定我应该使用哪种泛型类型,是字符串、int还是DateTime。
我可以在c#中解决这个问题吗?或者这只可能在动态语言中实现?
如果需要在大小写块中使用封闭泛型(如IThing<int>
),则不能这样做。
如果您不需要它,只需创建一个非泛型接口IThing
,从IThing<T>
派生。然后创建一个方法,根据枚举值创建适当的实例。
void Foo()
{
ProductType productType = GetProductType(userId);
SomeThingType someThingType = GetSomeThingTypeFromDb(userId);
switch(productType)
{
case ProductType.ONE:
IThing a = CreateThing(someThingType, ...);
break;
...
}
...
}
IThing CreateThing(SomeThingType someThingType , ...)
{
switch(someThingType )
{
case SomeThingType.X:
return new SomeThing<int>(...);
case SomeThingType.Y:
return new SomeThing<string>(...);
case SomeThingType.Z:
return new SomeThing<DateTime>(...);
default:
throw new ArgumentException(...);
}
}