■ 값 타입 변환하기 예제

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

using System;

 

string sourceValue = "10";

int    targetValue = (int)ConvertValueType(sourceValue, typeof(int));

 

Console.WriteLine("{0}, {1}", targetValue, targetValue.GetType());

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

 

■ 값 타입 변환하기

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

using System;

using System.ComponentModel;

using System.Globalization;

 

#region 값 타입 변환하기 - ConvertValueType(sourceValue, targetType, cultureInfo)

 

/// <summary>

/// 값 타입 변환하기

/// </summary>

/// <param name="sourceValue">소스 값</param>

/// <param name="targetType">타겟 타입</param>

/// <param name="cultureInfo">문화 정보</param>

/// <returns>타입 변환 값</returns>

public object ConvertValueType(object sourceValue, Type targetType, CultureInfo cultureInfo)

{

    if(sourceValue != null)

    {

        var sourceType = sourceValue.GetType();

 

        TypeConverter targetTypeConverter = TypeDescriptor.GetConverter(targetType);

 

        if(targetTypeConverter != null && targetTypeConverter.CanConvertFrom(sourceValue.GetType()))

        {

            return targetTypeConverter.ConvertFrom(null, cultureInfo, sourceValue);

        }

 

        TypeConverter sourceTypeConverter = TypeDescriptor.GetConverter(sourceType);

 

        if(sourceTypeConverter != null && sourceTypeConverter.CanConvertTo(targetType))

        {

            return sourceTypeConverter.ConvertTo(null, cultureInfo, sourceValue, targetType);

        }

 

        if(targetType.IsEnum && sourceValue is int)

        {

            return Enum.ToObject(targetType, (int)sourceValue);

        }

 

        if(!targetType.IsInstanceOfType(sourceValue))

        {

            return System.Convert.ChangeType(sourceValue, targetType, cultureInfo);

        }

    }

 

    return sourceValue;

}

 

#endregion

#region 값 타입 변환하기 - ConvertValueType(sourceValue, targetType)

 

/// <summary>

/// 값 타입 변환하기

/// </summary>

/// <param name="sourceValue">소스 값</param>

/// <param name="targetType">타겟 타입</param>

/// <returns>타입 변환 값</returns>

public object ConvertValueType(object sourceValue, Type targetType)

{

    return ConvertValueType(sourceValue, targetType, CultureInfo.InvariantCulture);

}

 

#endregion

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

Posted by 사용자 icodebroker
TAG