2013-12-21 4 views
2

난이 오브젝트에 Params는

class SomeObject 
    { 
     public int id { get; set; } 
     public string name {get;set;} 
     public string description {get;set;} 
     public anotherObject obj {get;set;} 
    } 

그 특성의 이름을 변수로 전송 nameis 경우리스트로부터 ㄱ PropertyInfo 제거이 확장 방법 있다고 가정

public static IList<PropertyInfo> Except(this IList<PropertyInfo> Properties, params string[] PropertiesToExecludeNames) 
     { 
      return Properties.Where(p => !(PropertiesToExecludeNames ?? Enumerable.Empty<String>()).Any(s => s == p.Name)).ToList(); 
     } 

및 나는 다음과 같이 사용한다.

var someObject = new SomeObject(); 
var Properties = someObject.GetType().GetProperties(); 
Properties = Properties.Except("name","obj"); 

나는 나쁜 것은 아니지만 나는 보내지 않는 방법을 찾고있다. IN 속성 이름을 문자열로 사용하면이 함수가 람다 식을 사용하도록 만들 수 있으므로 Exception에 속성을 쓰는 동안 Visual Studio에서 제안을 얻을 수 있습니까?

업데이트 :가 선택한 답변에 따라 다음도 지원 UnaryExpressions

public static IEnumerable<PropertyInfo> GetPropertyInfosExcept<T>(this T obj, params Expression<Func<T, object>>[] lambda) 
      { 
       HashSet<string> set = new HashSet<string>(
         lambda.Select(l => l.GetMemberInfo() as PropertyInfo) 
           .Select(x => x.Name)); 
       return typeof(T).GetProperties().Where(p => !set.Contains(p.Name)); 
      } 


public static MemberInfo GetMemberInfo(this LambdaExpression expression) 
      { 
       return expression.Body is MemberExpression ? ((MemberExpression)expression.Body).Member : ((MemberExpression)(((UnaryExpression)expression.Body).Operand)).Member; 
      } 

답변

3
var pInfos = new SomeObject().GetPropertyInfosExcept(x => x.obj, x => x.name) 
      .ToList(); 

public static IEnumerable<PropertyInfo> GetPropertyInfosExcept<T>(
          this T obj, params Expression<Func<T, object>>[] lambda) 
{ 
    HashSet<string> set = new HashSet<string>(
      lambda.Select(l => (l.Body as MemberExpression).Member as PropertyInfo) 
        .Select(x=>x.Name) 
     ); 

    return typeof(T).GetProperties().Where(p => !set.Contains(p.Name)); 
}