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
}