有没有办法使这个方法通用,所以我可以返回一个字符串,bool, int,或双精度?现在,它返回一个字符串,但如果它能够找到“true”或“false”作为配置值,我想返回一个bool值。
public static string ConfigSetting(string settingName)
{
return ConfigurationManager.AppSettings[settingName];
}
有没有办法使这个方法通用,所以我可以返回一个字符串,bool, int,或双精度?现在,它返回一个字符串,但如果它能够找到“true”或“false”作为配置值,我想返回一个bool值。
public static string ConfigSetting(string settingName)
{
return ConfigurationManager.AppSettings[settingName];
}
当前回答
您必须将方法的返回值的类型转换为调用期间传递给方法的泛型类型。
public static T values<T>()
{
Random random = new Random();
int number = random.Next(1, 4);
return (T)Convert.ChangeType(number, typeof(T));
}
您需要为通过该方法返回的值传递一个类型可种姓的类型。
如果您想要返回一个不能为所传递的泛型类型进行类型转换的值,则可能必须修改代码或确保为method的返回值传递一个可对其进行类型转换的类型。因此,不推荐使用这种方法。
其他回答
你需要让它成为一个泛型方法,就像这样:
public static T ConfigSetting<T>(string settingName)
{
return /* code to convert the setting to T... */
}
但是调用者必须指定他们所期望的类型。然后,您可能会使用Convert。ChangeType,假设所有相关类型都被支持:
public static T ConfigSetting<T>(string settingName)
{
object value = ConfigurationManager.AppSettings[settingName];
return (T) Convert.ChangeType(value, typeof(T));
}
请注意,我并不完全相信这是个好主意……
你可以使用Convert.ChangeType():
public static T ConfigSetting<T>(string settingName)
{
return (T)Convert.ChangeType(ConfigurationManager.AppSettings[settingName], typeof(T));
}
请尝试以下代码:
public T? GetParsedOrDefaultValue<T>(string valueToParse) where T : struct, IComparable
{
if(string.EmptyOrNull(valueToParse))return null;
try
{
// return parsed value
return (T) Convert.ChangeType(valueToParse, typeof(T));
}
catch(Exception)
{
//default as null value
return null;
}
return null;
}
有很多方法可以做到这一点(按优先级列出,具体到OP的问题)
Option 1: Straight approach - Create multiple functions for each type you expect rather than having one generic function. public static bool ConfigSettingInt(string settingName) { return Convert.ToBoolean(ConfigurationManager.AppSettings[settingName]); } Option 2: When you don't want to use fancy methods of conversion - Cast the value to object and then to generic type. public static T ConfigSetting<T>(string settingName) { return (T)(object)ConfigurationManager.AppSettings[settingName]; } Note - This will throw an error if the cast is not valid(your case). I would not recommend doing this if you are not sure about the type casting, rather go for option 3. Option 3: Generic with type safety - Create a generic function to handle type conversion. public static T ConvertValue<T,U>(U value) where U : IConvertible { return (T)Convert.ChangeType(value, typeof(T)); } Note - T is the expected type, note the where constraint here(type of U must be IConvertible to save us from the errors)
创建一个函数,并以泛型类型传递输出参数。
public static T some_function<T>(T output_object /*declare as Output object*/)
{
return output_object;
}