在C#中获得汇编描述的简化方法?

Den*_*els 13 c# linq reflection lambda .net-4.0

我正在阅读.NET 2.0书籍并遇到了这个获取应用程序程序集描述的示例代码:

static void Main(string[] args)
{
    Assembly assembly = Assembly.GetExecutingAssembly();
    object[] attributes = 
        assembly.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
    if (attributes.Length > 0)
    {
        AssemblyDescriptionAttribute descriptionAttribute =
            (AssemblyDescriptionAttribute)attributes[0];
        Console.WriteLine(descriptionAttribute.Description);
    }
    Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)

简单地获取程序集描述是相当多的代码,我想知道是否有更简单的方法在.NET 3.5+中使用LINQ或lambda表达式执行此操作?

jer*_*enh 28

真的没有.你可以这样做一点'更流利':

 var descriptionAttribute = assembly
         .GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false)
         .OfType<AssemblyDescriptionAttribute>()
         .FirstOrDefault();

 if (descriptionAttribute != null) 
     Console.WriteLine(descriptionAttribute.Description);
Run Code Online (Sandbox Code Playgroud)

[编辑将大会改为ICustomAttributeProvider,参见 Simon Svensson回答)

如果您需要这么多代码,请在ICustomAttributeProvider上创建一个扩展方法:

 public static T GetAttribute<T>(this ICustomAttributeProvider assembly, bool inherit = false) 
 where T : Attribute 
 {
     return assembly
         .GetCustomAttributes(typeof(T), inherit)
         .OfType<T>()
         .FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)


abh*_*ash 5

var attribute = Assembly.GetExecutingAssembly()
                    .GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false)
                    .Cast<AssemblyDescriptionAttribute>().FirstOrDefault();
if (attribute != null)
{
    Console.WriteLine(attribute.Description);
}
Run Code Online (Sandbox Code Playgroud)