C# 反射给 ValueType 子类赋值

发布时间 2023-10-26 22:46:45作者: 灵火
using System.Reflection;


string value = "100";
var counter = new Counter();
foreach (var propertyInfo in counter.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty))
{
    if (propertyInfo.PropertyType.IsSubclassOf(typeof(ValueType)))
    {
        var methodInfo = propertyInfo.PropertyType.GetMethod("Parse", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(string) }, null);
        var temp = methodInfo?.Invoke(null, new object[] { value });
        propertyInfo.SetValue(counter, temp);
    }
    else
    {
        propertyInfo.SetValue(counter, value);
    }
}

Console.WriteLine(counter.Count);
// output:
//   100


class Counter
{
    public int Count { get; set; }
}