2
我有一個字典,我想將其轉換爲循環中類的當前數據類型。擴展字符串,轉換爲數據類型
public static T ToClass<T>(this IDictionary<string, string> source) where T : class, new()
{
Type type = typeof(T);
T ret = new T();
foreach (var keyValue in source)
{
type.GetProperty(keyValue.Key).SetValue(ret, keyValue.Value.ToNullable<T>(), null);
}
return ret;
}
public static Nullable<T> ToNullable<T>(this string s) where T : struct
{
Nullable<T> result = new Nullable<T>();
try
{
if (!string.IsNullOrWhiteSpace(s))
{
TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
result = (T)conv.ConvertFrom(s);
}
}
catch { }
return result;
}
不知道HOWTO使keyValue.Value.ToNullable<T>()
工作,我希望它它轉換爲數據類型在迴路中的電流特性。
這個例子是如何完成的?
我試過這段代碼,不能讓它工作。
public static T TestParse<T>(this string value)
{
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}
你ToNullable是使用T型這是不正確的,是包含所有屬性的目標類的類型。你應該使用每個屬性的類型(不幸的是你沒有在字典中)。 – Strillo 2011-12-22 10:00:07
你有一個使它成爲不可空的轉換方法的例子嗎? – 2011-12-22 10:08:27