【问题标题】:Fetching the value that maps to an Enumeration, how to call the correct generically typed method?获取映射到枚举的值,如何调用正确的泛型类型方法?
【发布时间】:2011-10-25 18:18:44
【问题描述】:

我正在从数据库中获取 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# 中解决的问题吗?或者这只能在动态语言中实现?

【问题讨论】:

    标签: c# generics


    【解决方案1】:

    如果您需要在您的案例块中包含封闭的泛型类型(如IThing&lt;int&gt;),则不能这样做。

    如果您不需要它,只需创建一个非泛型接口IThing 派生自IThing&lt;T&gt;。然后有一个根据枚举值创建适当实例的方法。

    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(...);
        }
    }
    

    【讨论】:

    • 谢谢,我已经为 productType 分配了一些案例,这意味着我必须为每个案例编写一个 CreateThing 助手......我希望有一个更简单的方法!
    猜你喜欢
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 2020-08-01
    • 2012-08-03
    相关资源
    最近更新 更多