【问题标题】:How to determine the type of the returned value within the generic method如何确定泛型方法中返回值的类型
【发布时间】:2010-11-09 20:30:03
【问题描述】:

我们创建了一个像这样的通用方法:

公共TReturnType GetValue(字符串键) { var configurationParameter =(来自 _repository.ConfigurationParameters 中的 cp 其中 cp.ConfigurationParameterKey == 键 选择 cp).FirstOrDefault(); var returnValue (TReturnType)Convert.ChangeType(configurationParameter.ConfigurationParameterValue, typeof (TReturnType)); 返回返回值; }

现在,我们想在这个方法中加入一些错误处理,这样如果我们期望一个数字类型,我们可以做,例如,int.TryParse(returnValue, out myNewInt)。当然,要做到这一点,我们必须能够确定方法中 TReturnType 的类型。

有没有办法做到这一点?

感谢您的所有帮助。 问候。

【问题讨论】:

    标签: c# .net generics


    【解决方案1】:

    当然可以,但是您应该考虑这是否是一个好主意。你总是可以说

    if (typeof(T) == typeof(int)) whatever
    

    但是这样做有点难闻的代码味道。泛型的全部意义在于成为泛型。如果您有特殊用途代码用于 T 是整数时,那么为什么不简单地添加另一个方法 来精确处理整数情况?

    【讨论】:

    • 我在一个支持 3 种 id 的通用集合上完成了这项工作:字符串、整数和 guid。其他任何事情都会引发未实现的异常。
    • 最好只有三种方法。让你的泛型generic,这就是为什么我们称它们为generics
    【解决方案2】:

    当然,只需添加如下代码:

    if(typeof(TReturnType) == typeof(int))
    {
        var number = (int)returnValue;
        //Validate your output
    }
    

    【讨论】:

    • 天哪!!!这太简单了,真是太尴尬了。我现在肯定需要回家了。谢谢。
    猜你喜欢
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多