■ Convert 클래스의 ChangeType 정적 메소드를 사용해 값 타입을 변환하는 방법을 보여준다.
▶ Convert 클래스 : ChangeType 정적 메소드를 사용해 값 타입 변환하기 예제 (C#)
1 2 3 4 5 6 7 8 |
using System; string sourceValue = "10"; int targetValue = (int)ConvertValueType(sourceValue, typeof(int)); Console.WriteLine("{0}, {1}", targetValue, targetValue.GetType()); |
▶ Convert 클래스 : ChangeType 정적 메소드를 사용해 값 타입 변환하기 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
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 |