■ default 키워드를 사용해 객체 디폴트 값을 구하는 방법을 보여준다.
▶ TypeHelper.cs
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 |
using System.Reflection; namespace TestProject; /// <summary> /// 타입 헬퍼 /// </summary> public static class TypeHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 객체 디폴트 값 구하기 - GetObjectDefaultValue(sourceType) /// <summary> /// 객체 디폴트 값 구하기 /// </summary> /// <param name="sourceType">소스 타입</param> /// <returns>객체 디폴트 값</returns> public static object GetObjectDefaultValue(Type sourceType) { return typeof(TypeHelper).GetMethod ( "GetObjectDefaultValue", BindingFlags.NonPublic | BindingFlags.Static ) .MakeGenericMethod(sourceType) .Invoke(null, null); } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 객체 디폴트 값 구하기 - GetObjectDefaultValue<TSource>() /// <summary> /// 객체 디폴트 값 구하기 /// </summary> /// <typeparam name="TSource">소스 타입</typeparam> /// <returns>객체 디폴트 값</returns> private static TSource GetObjectDefaultValue<TSource>() { return default(TSource); } #endregion } |
▶ Program.cs
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 |
namespace TestProject; /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { Console.WriteLine(TypeHelper.GetObjectDefaultValue(typeof(int ))); Console.WriteLine(TypeHelper.GetObjectDefaultValue(typeof(string ))); Console.WriteLine(TypeHelper.GetObjectDefaultValue(typeof(DateTime))); } #endregion } |