2016-06-07 1 views
0

람다 - 메서드 구문을 작성할 때 특성이있는 모든 클래스에 대해 각 클래스 이름과 해당 특성을 인쇄하는 함수를 원합니다.C# linq - lambda 식의 로컬 문자열 변수 만들기

var x1 = Assembly.GetExecutingAssembly() 
    .GetTypes() 
    .Select(type => type 
     .GetCustomAttributes(false) 
     .Select(attribute => type.Name + " - " + attribute.ToString()) 
     .ToList()) 
    .ToList(); 

x1.ForEach(type => type.ForEach(str => Console.WriteLine(str))); 

출력 :

<ClassName> - <ProgramName>.<AttributeName> 
<ClassName> - <ProgramName>.<AttributeName> 
<>c__DisplayClass6 - System.Runtime.CompilerServices.CompilerGeneratedAttribute 

I 로컬 람다 식 변수를 사용하기 때문에, 출력의 마지막 행이 있는지 이해한다.

마지막 행을 표시하지 않으려면 어떻게해야합니까? 유형이 그런 CompilerGeneratedAttribute이있는 경우

+2

if (type.IsDefined (typeof (CompilerGeneratedAttribute), false))를 확인하고 건너 뛸 수 있습니다. – riteshmeher

+0

감사합니다! 그것은 작동합니다. –

+0

당신을 도울 수있어서 기쁩니다! – riteshmeher

답변

0

확인해 볼 수 있습니다 : 타입이 (대신 개발자의) 컴파일러에 의해 생성

var x1 = Assembly.GetExecutingAssembly() 
    .GetTypes().Where(type => type.GetCustomAttribute<CompilerGeneratedAttribute>() == null) 
    .Select(type => type.GetCustomAttributes(false) 
     .Select(attribute => type.Name + " - " + attribute.ToString()) 
    .ToList()).ToList(); 

경우, 해당 유형이 CompilerGeneratedAttribute 있습니다. 위의 코드에서 Where()은이 특성을 가진 모든 유형을 걸러냅니다.

0
var x1 = Assembly.GetExecutingAssembly() 
    .GetTypes() 
    .Where(type => !type.IsDefined(typeof(CompilerGeneratedAttribute), false))) 
    .Select(type => type 
     .GetCustomAttributes(false) 
     .Select(attribute => type.Name + " - " + attribute.ToString()) 
     .ToList()) 
    .ToList(); 

x1.ForEach(type => type.ForEach(str => Console.WriteLine(str))); 
0

주석에서 언급 한.

var x1 = Assembly.GetExecutingAssembly() 
      .GetTypes() 
      .Where(type=>!type.IsDefined(typeof(CompilerGeneratedAttribute), false)) 
      .Select(type => type 
       .GetCustomAttributes(false) 
       .Select(attribute => type.Name + " - " + attribute.ToString()) 
       .ToList()) 
      .ToList(); 
      x1.ForEach(type => type.ForEach(Console.WriteLine)); 

link을 확인할 수 있습니다. CompilerGeneratedAttribute의 올바른 사용법을 알려줍니다.