■ dynamic 타입 객체의 속성 포함 여부를 구하는 방법을 보여준다.
▶ DynamicHelper.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 52 |
using System.Dynamic; using System.Linq.Expressions; namespace TestProject; public static class DynamicHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 멤버 소유 여부 구하기 - HasMember(dynamicObject, memberName) /// <summary> /// 멤버 소유 여부 구하기 /// </summary> /// <param name="dynamicObject">동적 객체</param> /// <param name="memberName">멤버명</param> /// <returns>멤버 소유 여부</returns> public static bool HasMember(object dynamicObject, string memberName) { return GetMemberNameEnumerable(dynamicObject).Contains(memberName); } #endregion #region 멤버명 열거 가능형 구하기 - GetMemberNameEnumerable(dynamicObject) /// <summary> /// 멤버명 열거 가능형 구하기 /// </summary> /// <param name="dynamicObject">동적 객체</param> /// <returns>멤버명 열거 가능형</returns> public static IEnumerable<string> GetMemberNameEnumerable(object dynamicObject) { IDynamicMetaObjectProvider provider = dynamicObject as IDynamicMetaObjectProvider; if(provider == null) { throw new InvalidOperationException("제공된 개체는 dynamic 개체여야 합니다(즉, IDynamicMetaObjectProvider를 구현해야 함)."); } DynamicMetaObject dynamicMetaObject = provider.GetMetaObject(Expression.Constant(provider)); IEnumerable<string> memberNameEnumerable = dynamicMetaObject.GetDynamicMemberNames(); return memberNameEnumerable; } #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 28 29 30 31 32 33 34 35 |
using System.Dynamic; namespace TestProject; /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { dynamic x = new ExpandoObject(); x.Name = "홍길동"; x.Age = "21"; if(DynamicHelper.HasMember(x, "Age")) { Console.WriteLine("Age = {0}", x.Age); } } #endregion } |