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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM