gpt4 book ai didi

c# - 扩展字符串,转换为数据类型

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:32 24 4
gpt4 key购买 nike

我有一个字典,我想将它转换为循环中类的当前数据类型。

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);
}

最佳答案

尝试以下操作:

/// <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>();
}
}

关于c# - 扩展字符串,转换为数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8602077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com