📜  c# 复制每个属性 - C# 代码示例

📅  最后修改于: 2022-03-11 14:49:20.489000             🧑  作者: Mango

代码示例1
public static void CopyPropertiesTo(this T source, TU dest)
{
    var sourceProps = typeof (T).GetProperties().Where(x => x.CanRead).ToList();
    var destProps = typeof(TU).GetProperties()
            .Where(x => x.CanWrite)
            .ToList();

    foreach (var sourceProp in sourceProps)
    {
        if (destProps.Any(x => x.Name == sourceProp.Name))
        {
            var p = destProps.First(x => x.Name == sourceProp.Name);
            if(p.CanWrite) { // check if the property can be set or no.
                p.SetValue(dest, sourceProp.GetValue(source, null), null);
            }
        }

    }

}