小编tjh*_*jh7的帖子

C#Reflection - 将两个对象合并在一起

我需要更新对象A的属性,如果null为对象B的等效属性,如果它不为null.我想要可以用于各种对象的代码.

我有一个版本工作,直到其中一个对象包含List类型的属性,这是我在下面的代码中有空白的地方.我的主要问题是如何才能最好地实现这部分代码.其次是有更好的方法来做这件事,第三,我知道它永远不会很快,但任何加快它的建议都会受到赞赏.

提前致谢.

public T MergeWith<T, U>(T primarySource, U secondarySource) where U : class, T
    {
        Type primaryType = typeof(T);
        Type secondaryType = typeof(U);
        foreach (PropertyInfo primaryInfo in primaryType.GetProperties())
        {
            if (primaryInfo.CanWrite)
            {
                object currentPrimary = primaryInfo.GetValue(primarySource, null);

                PropertyInfo secondaryInfo = secondaryType.GetProperty(primaryInfo.Name);
                object currentSecondary = secondaryInfo.GetValue(secondarySource, null);

                if (currentPrimary == null && currentSecondary != null)
                {
                    primaryInfo.SetValue(primarySource, currentSecondary, null);
                }
                else if ((currentPrimary != null && currentSecondary != null) && isChildClass(primaryInfo))
                {
                    if (isCollection(currentPrimary))
                    {
                        // here


                    }
                    else
                    { …
Run Code Online (Sandbox Code Playgroud)

c#

2
推荐指数
1
解决办法
3905
查看次数

标签 统计

c# ×1