我有一个字典,我想把它转换为循环中类的当前数据类型。
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;
}
不确定如何使keyValue.Value.ToNullable<T>()
起作用,我希望它将它转换为循环中当前属性的数据类型。
在这个例子中如何完成?
我已经尝试过这段代码,无法让它发挥作用。
public static T TestParse<T>(this string value)
{
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}
答案 0 :(得分:2)
尝试以下方法:
/// <summary>
/// ClassExtensions
/// </summary>
static class ClassExtensions
{
/// <summary>
/// Converts an object to nullable.
/// </summary>
/// <typeparam name="P">The object type</typeparam>
/// <param name="s">The object value.</param>
/// <returns></returns>
public static Nullable<P> ToNullable<P>(this string s) where P : struct
{
Nullable<P> result = new Nullable<P>();
try
{
if (!string.IsNullOrWhiteSpace(s))
{
TypeConverter conv = TypeDescriptor.GetConverter(typeof(P));
result = (P)conv.ConvertFrom(s);
}
}
catch { }
return result;
}
/// <summary>
/// Converts a dictionary of property values into a class.
/// </summary>
/// <typeparam name="T">The class type.</typeparam>
/// <param name="source">The properties dictionary.</param>
/// <returns>An instance of T with property values set to the values defined in the dictionary.</returns>
public static T ToClass<T>(this IDictionary<string, string> source) where T : class, new()
{
Type classType = typeof(T);
T returnClass = new T();
foreach (var keyValue in source)
{
PropertyInfo prop = classType.GetProperty(keyValue.Key);
MethodInfo method = typeof(ClassExtensions).GetMethod("ToNullable");
MethodInfo generic = method.MakeGenericMethod(prop.PropertyType);
object convertedValue = generic.Invoke(keyValue.Value, new object[] { keyValue.Value });
prop.SetValue(returnClass, convertedValue, null);
}
return returnClass;
}
}
/// <summary>
/// TestClass
/// </summary>
class TestClass
{
public int Property1 { get; set; }
public long Property2 { get; set; }
}
/// <summary>
/// Program.
/// </summary>
class Program
{
static void Main(string[] args)
{
IDictionary<string, string> properties = new Dictionary<string, string> { { "Property1", "1" }, { "Property2", "2" } };
properties.ToClass<TestClass>();
}
}