如何获得AssemblyTitle?

我知道Assembly.GetExecutingAssembly()的.NET Core替换是typeof(MyType).GetTypeInfo().Assembly ,但是替换为

 Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false) 

我已经尝试在组装之后附加代码的最后一位用于提到的第一个解决方案,如下所示:

 typeof(VersionInfo).GetTypeInfo().Assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute)); 

但它给了我一个“不能隐式转换为object []的消息。

更新:是的,正如下面的评论所示,我认为它与输出类型相关联。

这是代码片段,我只是想将其更改为与.Net Core兼容:

 public class VersionInfo { public static string AssemlyTitle { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false); // More code follows 

我已经尝试将其更改为使用CustomAttributeExtensions.GetCustomAttributes(但我目前不了解c#以了解如何实现与上面相同的代码。我仍然对MemberInfo和Type等有所了解。非常感谢任何帮助!

我怀疑问题出在你没有显示的代码中:你在哪里使用GetCustomAttributes()的结果。 这是因为.Net Framework中的Assembly.GetCustomAttributes(Type, bool)返回object[] ,而.Net Core中的CustomAttributeExtensions.GetCustomAttributes(this Assembly, Type)返回IEnumerable

所以你需要相应地修改你的代码。 最简单的方法是使用.ToArray() ,但更好的解决方案可能是更改代码,以便它可以使用IEnumerable

这适用于.NET Core 1.0:

 using System; using System.Linq; using System.Reflection; namespace SO_38487353 { public class Program { public static void Main(string[] args) { var attributes = typeof(Program).GetTypeInfo().Assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute)); var assemblyTitleAttribute = attributes.SingleOrDefault() as AssemblyTitleAttribute; Console.WriteLine(assemblyTitleAttribute?.Title); Console.ReadKey(); } } } 

AssemblyInfo.cs中

 using System.Reflection; [assembly: AssemblyTitle("My Assembly Title")] 

project.json

 { "buildOptions": { "emitEntryPoint": true }, "dependencies": { "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.0" }, "System.Runtime": "4.1.0" }, "frameworks": { "netcoreapp1.0": { } } } 

这对我有用:

 public static string GetAppTitle() { AssemblyTitleAttribute attributes = (AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false); return attributes?.Title; } 

这不是最简单的吗?

 string title = Assembly.GetExecutingAssembly().GetCustomAttribute().Title; 

只是在说。

这就是我用的:

 private string GetApplicationTitle => ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false))?.Title ?? "Unknown Title";