C# 反射 循环属性、字段赋值

private static void CopyValueToTarget<T>(T source, T target) where T:class
{
    Type type = source.GetType();
    var fields= type.GetRuntimeFields().ToList();
    foreach(var field in fields)
    {
        field.SetValue(target, field.GetValue(source));
    }
    
    var properties = type.GetRuntimeProperties().ToList();
    foreach (var property in properties)
    {
        property.SetValue(target, property.GetValue(source));
    }
}
//测试
Fish fish = new Fish() { Name = "ccc", Weight = (decimal)9.7 };
Fish copyFish = new Fish();
CopyValueToTarget<Fish>(fish, copyFish);

GetRuntimeFields和GetFields

根据官方说法,
GetRuntimeFields是检索表示指定类型定义的所有字段的集合。
GetFields是返回当前 Type 的所有公共字段。
GetRuntimeProperties和GetProperties、GetRuntimeEvents和GetEvents等方法可以类推。

示例代码

ReflectionDemo

原文地址:https://www.cnblogs.com/Lulus/p/12886502.html