첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

▶ Convert 클래스 : ChangeType 정적 메소드를 사용해 지정 타입으로 변환하기 예제

using System;

int  value1 = ConversionHelper.Convert<int>("14");
int? value2 = ConversionHelper.Convert<int?>("14");

Console.WriteLine(value1);
Console.WriteLine(value2);

 

728x90

 

▶ Convert 클래스 : ChangeType 정적 메소드를 사용해 지정 타입으로 변환하기

using System;

/// <summary>
/// 변환 헬퍼
/// </summary>
public static class ConversionHelper
{
    //////////////////////////////////////////////////////////////////////////////////////////////////// Method
    ////////////////////////////////////////////////////////////////////////////////////////// Static
    //////////////////////////////////////////////////////////////////////////////// Public

    #region 변환하기 - Convert(sourceValue, targetType)

    /// <summary>
    /// 변환하기
    /// </summary>
    /// <param name="sourceValue">소스 값</param>
    /// <param name="targetType">타겟 타입</param>
    /// <returns>변환 값</returns>
    public static object Convert(object sourceValue, Type targetType)
    {
        Type underlyingType = Nullable.GetUnderlyingType(targetType);

        if(underlyingType != null && sourceValue == null)
        {
            return null;
        }

        Type basetype = underlyingType == null ? targetType : underlyingType;

        return System.Convert.ChangeType(sourceValue, basetype);
    }

    #endregion
    #region 변환하기 - Convert<TTarget>(sourceValue)

    /// <summary>
    /// 변환하기
    /// </summary>
    /// <typeparam name="TTarget">타겟 타입</typeparam>
    /// <param name="sourceValue">소스 값</param>
    /// <returns>변환 값</returns>
    public static TTarget Convert<TTarget>(object sourceValue)
    {
        return (TTarget)Convert(sourceValue, typeof(TTarget));
    }

    #endregion
}
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요