如何让我的方法的返回类型通用? [英] How do I make the return type of a method generic?

查看:146
本文介绍了如何让我的方法的返回类型通用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法,使这种方法一般这样我就可以返回一个字符串,BOOL,INT,或双?现在,它的返回一个字符串,但如果它能够找到真或假的配置价值,我想返回一个布尔值,例如

 公共静态字符串ConfigSetting(字符串settingName)
    {
         返回ConfigurationManager.AppSettings [settingName]
    }
 

解决方案

您需要使它成为一个通用的方法,像这样的:

 公共静态牛逼ConfigSetting< T>(字符串settingName)
{
    返回/ * code转换的设置来的... * /
}
 

不过的来电的必须指定他们期望的类型。然后,您可能使用 Convert.ChangeType ,假设所有相关类型的支持:

 公共静态牛逼ConfigSetting< T>(字符串settingName)
{
    对象值= ConfigurationManager.AppSettings [settingName]
    返程(T)Convert.ChangeType(值的typeof(T));
}
 

我不完全相信,这一切是个好主意,你要知道...

Is there a way to make this method generic so I can return a string, bool, int, or double? Right now, it's returning a string, but if it's able find "true" or "false" as the configuration value, I'd like to return a bool for example.

    public static string ConfigSetting(string settingName)
    {  
         return ConfigurationManager.AppSettings[settingName];
    }

解决方案

You need to make it a generic method, like this:

public static T ConfigSetting<T>(string settingName)
{  
    return /* code to convert the setting to T... */
}

But the caller will have to specify the type they expect. You could then potentially use Convert.ChangeType, assuming that all the relevant types are supported:

public static T ConfigSetting<T>(string settingName)
{  
    object value = ConfigurationManager.AppSettings[settingName];
    return (T) Convert.ChangeType(value, typeof(T));
}

I'm not entirely convinced that all this is a good idea, mind you...

这篇关于如何让我的方法的返回类型通用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆