■ 속성 값 설정하기 예제

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

using System;

 

public class Student

{

    public string Name { get; set; }

}

 

Student student = new Student();

            

SetPropertyValue(student, "Name", "홍길동");

 

Console.WriteLine(student.Name);

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

 

■ 속성 값 설정하기

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

using System;

using System.Reflection;

 

#region 속성 값 설정하기 - SetPropertyValue(instance, propertyName, value)

 

/// <summary>

/// 속성 값 설정하기

/// </summary>

/// <param name="instance">인스턴스</param>

/// <param name="propertyName">속성명</param>

/// <param name="value"></param>

public void SetPropertyValue(object instance, string propertyName, object value)

{

    if(instance == null)

    {

        throw new ArgumentNullException("instance");

    }

 

    if(string.IsNullOrWhiteSpace(propertyName))

    {

        throw new ArgumentNullException("propertyName");

    }

 

    Type objectType = instance.GetType();

 

    PropertyInfo propertyInfo = objectType.GetProperty(propertyName);

 

    if(propertyInfo == null)

    {

        throw new Exception

        (

            string.Format

            (

                "No property '{0}' found on the instance of type '{1}'.",

                propertyName,

                objectType

            )

        );

    }

 

    if(!propertyInfo.CanWrite)

    {

        throw new Exception

        (

            string.Format

            (

                "The property '{0}' on the instance of type '{1}' does not have a setter.",

                propertyName,

                objectType

            )

        );

    }

 

    if(value != null && !value.GetType().IsAssignableFrom(propertyInfo.PropertyType))

    {

        value = ConvertValueType(value, propertyInfo.PropertyType); // '값 타입 변환하기' 참조

    }

 

    propertyInfo.SetValue(instance, value, new object[0]);

}

 

#endregion

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

Posted by 사용자 icodebroker

댓글을 달아 주세요