첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
유용한 소스 코드가 있으면 icodebroker@naver.com으로 보내주시면 감사합니다.
블로그 자료는 자유롭게 사용하세요.

■ 객체 값 복사하기

------------------------------------------------------------------------------------------------------------------------

using System;

using System.Linq;

using System.Reflection;

 

#region 값 복사하기 - CopyValue(source, target, excludePropertyList, bindingFlags)

 

/// <summary>

/// 값 복사하기

/// </summary>

/// <param name="source">소스 객체</param>

/// <param name="target">타겟 객체</param>

/// <param name="excludePropertyList">제외 속성 리스트</param>

/// <param name="bindingFlags">바인딩 플래그</param>

/// <remarks>

/// BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase

/// </remarks>

public void CopyValue(object source, object target, string excludePropertyList, BindingFlags bindingFlags)

{

    string[] excludePropertyArray = null;

 

    if(!string.IsNullOrEmpty(excludePropertyList))

    {

        excludePropertyArray = excludePropertyList.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);

    }

 

    MemberInfo[] memnerInfoArray = target.GetType().GetMembers(bindingFlags);

 

    foreach(MemberInfo memnerInfo in memnerInfoArray)

    {

        string memberName = memnerInfo.Name;

 

        if(!string.IsNullOrEmpty(excludePropertyList) && excludePropertyArray.Contains(memberName))

        {

            continue;

        }

 

        if(memnerInfo.MemberType == MemberTypes.Field)

        {

            FieldInfo sourceFieldInfo = source.GetType().GetField(memberName);

 

            if(sourceFieldInfo == null)

            {

                continue;

            }

 

            object sourceValue = sourceFieldInfo.GetValue(source);

 

            ((FieldInfo)memnerInfo).SetValue(target, sourceValue);

        }

        else if(memnerInfo.MemberType == MemberTypes.Property)

        {

            PropertyInfo targetPropertyInfo = memnerInfo as PropertyInfo;

            PropertyInfo sourcePropertyInfo = source.GetType().GetProperty(memberName, bindingFlags);

 

            if(sourcePropertyInfo == null)

            {

                continue;

            }

 

            if(targetPropertyInfo.CanWrite && sourcePropertyInfo.CanRead)

            {

                object SourceValue = sourcePropertyInfo.GetValue(source, null);

 

                targetPropertyInfo.SetValue(target, SourceValue, null);

            }

        }

    }

}

 

#endregion

------------------------------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker

댓글을 달아 주세요