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

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

问题描述

有没有办法让这个方法通用,这样我就可以返回一个字符串、布尔值、整数或双精度值?现在,它返回一个字符串,但如果它能够找到true"或false"作为配置值,我想返回一个布尔值.

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... */
}

但是调用者必须指定他们期望的类型.然后您可以潜在地使用 Convert.ChangeType,假设所有支持相关类型:

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天全站免登陆