有没有办法使这个方法通用,所以我可以返回一个字符串,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 static T some_function<T>(T output_object /*declare as Output object*/)
{
return output_object;
}
private static T[] prepareArray<T>(T[] arrayToCopy, T value)
{
Array.Copy(arrayToCopy, 1, arrayToCopy, 0, arrayToCopy.Length - 1);
arrayToCopy[arrayToCopy.Length - 1] = value;
return (T[])arrayToCopy;
}
I was performing this throughout my code and wanted a way to put it into a method. I wanted to share this here because I didn't have to use the Convert.ChangeType for my return value. This may not be a best practice but it worked for me. This method takes in an array of generic type and a value to add to the end of the array. The array is then copied with the first value stripped and the value taken into the method is added to the end of the array. The last thing is that I return the generic array.
请尝试以下代码:
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;
}