你必須知道預期類型 如果你這樣做你可以使用的TypeConverter如:
public object DetectType(string stringValue)
{
var expectedTypes = new List<Type> {typeof (DateTime), typeof (int)};
foreach (var type in expectedTypes)
{
TypeConverter converter = TypeDescriptor.GetConverter(type);
if (converter.CanConvertFrom(typeof(string)))
{
try
{
// You'll have to think about localization here
object newValue = converter.ConvertFromInvariantString(stringValue);
if (newValue != null)
{
return newValue;
}
}
catch
{
// Can't convert given string to this type
continue;
}
}
}
return null;
}
大多數系統類型都有自己的類型轉換器,你可以使用你的類的TypeConverter屬性,並實現自己的轉換器編寫自己的
你需要寫你自己....讓我想知道你爲什麼需要那個...... – 2010-10-26 06:19:49