728x90
728x170
▶ Product.cs
namespace TestProject;
/// <summary>
/// 제품
/// </summary>
public class Product
{
//////////////////////////////////////////////////////////////////////////////////////////////////// Property
////////////////////////////////////////////////////////////////////////////////////////// Public
#region 제품 코드 - ProductCode
/// <summary>
/// 제품 코드
/// </summary>
public string ProductCode { get; set; }
#endregion
#region 명칭 - Name
/// <summary>
/// 명칭
/// </summary>
public string Name { get; set; }
#endregion
#region 가격 - Price
/// <summary>
/// 가격
/// </summary>
public decimal Price { get; set; }
#endregion
}
728x90
▶ PropertyHelper.cs
using System.Linq.Expressions;
using System.Reflection;
namespace TestProject;
/// <summary>
/// 속성 헬퍼
/// </summary>
/// <typeparam name="TSource">소스 타입</typeparam>
public static class PropertyHelper<TSource>
{
//////////////////////////////////////////////////////////////////////////////////////////////////// Method
////////////////////////////////////////////////////////////////////////////////////////// Static
//////////////////////////////////////////////////////////////////////////////// Public
#region 속성 정보 구하기 - GetPropertyInfo<TProperty>(selector)
/// <summary>
/// 속성 정보 구하기
/// </summary>
/// <typeparam name="TProperty">속성 타입</typeparam>
/// <param name="selector">셀렉터</param>
/// <returns>속성 정보</returns>
public static PropertyInfo GetPropertyInfo<TProperty>(Expression<Func<TSource, TProperty>> selector)
{
Expression body = selector;
if(body is LambdaExpression)
{
body = ((LambdaExpression)body).Body;
}
switch(body.NodeType)
{
case ExpressionType.MemberAccess : return (PropertyInfo)((MemberExpression)body).Member;
default : throw new InvalidOperationException();
}
}
#endregion
}
300x250
▶ Program.cs
using System.Reflection;
namespace TestProject;
/// <summary>
/// 프로그램
/// </summary>
class Program
{
//////////////////////////////////////////////////////////////////////////////////////////////////// Method
////////////////////////////////////////////////////////////////////////////////////////// Static
//////////////////////////////////////////////////////////////////////////////// Private
#region 프로그램 시작하기 - Main()
/// <summary>
/// 프로그램 시작하기
/// </summary>
private static void Main()
{
Product product = new Product { ProductCode = "0001", Name = "제품A", Price = 25_000 };
PropertyInfo propertyInfo = PropertyHelper<Product>.GetPropertyInfo(x => x.Name);
Console.WriteLine(propertyInfo.GetValue(product));
}
#endregion
}
728x90
그리드형(광고전용)