2012-04-18 12 views
12

estaba leyendo un libro .NET 2.0 y encontré este código de ejemplo que se pone la descripción de montaje aplicaciones:¿Forma simplificada de obtener la descripción del ensamblaje en C#?

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

Es un buen montón de código para conseguir simplemente la descripción de montaje y me gustaría saber si hay una manera más simple de hacer esto en .NET 3.5+ usando expresiones LINQ o lambda?

+7

Creo que este código es lo suficientemente bueno para –

Respuesta

27

No hay, realmente. Puede que sea un poco 'más fluida' como esto:

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

if (descriptionAttribute != null) 
    Console.WriteLine(descriptionAttribute.Description); 

[EDIT cambió Asamblea a ICustomAttributeProvider, cf. responder por Simon Svensson)

Y si necesita este tipo de código mucho, hacer un método de extensión en ICustomAttributeProvider:

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

Si bien este código ya es relativamente concisa, que podía apalancamiento un poco de LINQ para limpiarlo un toque.

AssemblyDescriptionAttribute attribute = assembly 
    .GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false) 
    .OfType<AssemblyDescriptionAttribute>() 
    .SingleOrDefault(); 

if(attribute != null) 
{ 
    Console.WriteLine(attribute.Description); 
} 
4

me gustaría utilizar un método de extensión para ICustomAttributeProvider para proporcionar un establecimiento inflexible GetCustomAttributes que devuelve un establecimiento inflexible enumerable. El único uso de LINQ sería la llamada a FirstOrDefault y OfType

public static void Main() { 
    Assembly assembly = Assembly.GetExecutingAssembly(); 
    var descriptionAttribute = assembly 
     .GetCustomAttributes<AssemblyDescriptionAttribute>(inherit: false) 
     .FirstOrDefault(); 

    if (descriptionAttribute != null) { 
     Console.WriteLine(descriptionAttribute.Description); 
    } 

    Console.ReadKey(); 
} 

public static IEnumerable<T> GetCustomAttributes<T>(this ICustomAttributeProvider provider, bool inherit) where T : Attribute { 
    return provider.GetCustomAttributes(typeof(T), inherit).OfType<T>(); 
} 
4
var attribute = Assembly.GetExecutingAssembly() 
        .GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false) 
        .Cast<AssemblyDescriptionAttribute>().FirstOrDefault(); 
if (attribute != null) 
{ 
    Console.WriteLine(attribute.Description); 
} 
+1

1 '()'. – abatishchev

1

me gustaría hacer algo como esto:

public static class AssemblyExtensions 
{ 
    public static string GetDescription(this Assembly assembly) 
    { 
     var attribute = assembly.GetCustomAttributes(typeof (AssemblyDescriptionAttribute), false) 
      .Select(a => a as AssemblyDescriptionAttribute).FirstOrDefault(); 

     if (attribute == null) 
     { 
      return String.Empty; 
     } 

     return attribute.Description; 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var assembly = Assembly.GetExecutingAssembly(); 
     Console.WriteLine(assembly.GetDescription()); 
     Console.ReadKey(); 
    } 
} 
0

Aquí tienes - se condensa fácilmente a dos líneas de código - - y si eso es demasiado grande, se puede volcar en un método de extensión:

public static string GetAssemblyDescription(this Assembly assembly) 
{ 
    return assembly.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false) 
     .OfType<AssemblyDescriptionAttribute>().SingleOrDefault()?.Description; 
} 

Entonces sólo tiene que utilizar el método de extensión de esta manera:

Console.WriteLine(typeof(Program).Assembly.GetAssemblyDescription()); 
1

Siguiendo @ ab-Kolan respuesta, que podría ser aún más simple:

var description = Assembly 
      .GetExecutingAssembly() 
      .GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false) 
      .OfType<AssemblyDescriptionAttribute>() 
      .FirstOrDefault()? 
      .Description ?? ""; 
0

Si sólo estás interesado en el proceso de ejecución actual (frente ensamblaje de acuerdo con el post original), entonces es una simple forro ..

Console.WriteLine(Process.GetCurrentProcess().MainModule.FileVersionInfo.Comments); 
Cuestiones relacionadas