我做了一个程序,我想根据参数类型转换所有值,这是通过运行时方法得到的,我想要的是将所有值用户在文本框中输入参数的定义类型。 我想要的是将字符串类型转换为int,float,decimal等类型在运行时C#
private object convertType(Type type, string value)
{
Type t = typeof(int);
//suppose value have stringvalue=33;
return 33; //of type int
}
有什么办法得到任何对象类型?
更新回答
为@Atmane EL BOUACHRI,
class Program
{
static void Main()
{
var ints = ConvertType<int>("33");
var bools = ConvertType<bool>("false");
var decimals = ConvertType<decimal>("1.33m"); // exception here
Console.WriteLine(ints);
Console.WriteLine(bools);
Console.WriteLine(decimals);
Console.ReadLine();
}
public static T ConvertType<T>(string input)
{
T result = default(T);
var converter = TypeDescriptor.GetConverter(typeof(T));
if (converter != null)
{
try
{
result = (T)converter.ConvertFromString(input);
}
catch
{
// add you exception handling
}
}
return result;
}
}
在这里,我不想硬编码<int>
,<string>
或<decimal>
,我要的是
private object convertToAnyType(Type type, string value)
{
//Type t = typeof(int);
return ConvertType<type>("33");
}
有什么办法吗?
你可能不得不使用泛型。 –
我做了一个动态的Web服务调用,其中任何Web服务都被我的项目占用,但是我被卡住了不同类型的参数,我如何处理不同方法的所有参数? –
'Convert.ChangeType'将适用于有限范围的内置类型 –