簡體   English   中英

C#在linq中創建本地字符串變量-Lambda表達式

[英]C# Creating a local string variable in linq - lambda expression

當編寫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 

我知道輸出的最后一行是因為使用了本地lambda表達式變量。

如何避免顯示最后一行?

您可以檢查類型是否具有CompilerGeneratedAttribute這樣的內容:

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()過濾掉所有具有此屬性的類型。

 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)));

如評論中所述。

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));

您可以檢查此鏈接 它告訴您有關CompilerGeneratedAttribute的正確用法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM