value = Convert.ChangeType(value,typeof(string))
这么转有什么意义呢?他和value.ToString()有什么区别?
Convert.ChangeType一般在什么时候用呢?
如果你知道当前类型应当为string的话,没有意义,ChangeType往往用在不知道当前类型应当是什么的情况下,比如有个泛型方法
T GetObject<T>(string str)
要求从string类型转换为指定的T类型,此时只能
return (T)Convert.ChangeType(str, typeof(T));
因为str显式转为T肯定是不行的,只能ChangeType。
ChangeType 是将 value 指定的对象转换为 conversionType 的通用转换方法。 value 参数可以是任何类型的对象,conversionType 也可以是表示任何基类型或自定义类型的 Type 对象。 要使转换成功,value 必须实现 IConvertible 接口,因为此方法只是包装对相应 IConvertible 方法的调用。 此方法要求支持将 value 转换为 conversionType。
using System;
public class ChangeTypeTest {
public static void Main() {
Double d = -2.345;
int i = (int)Convert.ChangeType(d, typeof(int));
Console.WriteLine("The double value {0} when converted to an int becomes {1}", d, i);
string s = "12/12/98";
DateTime dt = (DateTime)Convert.ChangeType(s, typeof(DateTime));
Console.WriteLine("The string value {0} when converted to a Date becomes {1}", s, dt);
}
}
using System;
public enum Continent
{
Africa, Antarctica, Asia, Australia, Europe,
NorthAmerica, SouthAmerica
};
public class Example
{
public static void Main()
{
// Convert a Continent to a Double.
Continent cont = Continent.NorthAmerica;
Console.WriteLine("{0:N2}",
Convert.ChangeType(cont, typeof(Double)));
// Convert a Double to a Continent.
Double number = 6.0;
try {
Console.WriteLine("{0}",
Convert.ChangeType(number, typeof(Continent)));
}
catch (InvalidCastException) {
Console.WriteLine("Cannot convert a Double to a Continent");
}
Console.WriteLine("{0}", (Continent) number);
}
}
// The example displays the following output:
// 5.00
// Cannot convert a Double to a Continent
// SouthAmerica
ChangeType(Object, Type) 方法能将可以将空类型转换为另一种类型。
但是,它无法将另一种类型转换为空类型,即使 conversionType 是 Nullable<T>的基础类型。
执行这个转换,你可以使用强制类型转换符(在 C# 中)或一个转换函数(在 Visual Basic 中)。
下面的示例说明转换到/从空类型。
using System;
public class Example
{
public static void Main()
{
int? intValue1 = 12893;
double dValue1 = (double) Convert.ChangeType(intValue1, typeof(Double));
Console.WriteLine("{0} ({1})--> {2} ({3})", intValue1, intValue1.GetType().Name,
dValue1, dValue1.GetType().Name);
float fValue1 = 16.3478f;
int? intValue2 = (int) fValue1;
Console.WriteLine("{0} ({1})--> {2} ({3})", fValue1, fValue1.GetType().Name,
intValue2, intValue2.GetType().Name);
}
}
// The example displays the following output:
// 12893 (Int32)--> 12893 (Double)
// 16.3478 (Single)--> 16 (Int32)