如何获得AssemblyTitle?

时间:2016-07-20 17:44:41

标签: c# .net .net-core

我知道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之类的东西我还是混淆了。非常感谢任何帮助!

5 个答案:

答案 0 :(得分:9)

我怀疑问题出在您未显示的代码中:您使用GetCustomAttributes()的结果。这是因为Assembly.GetCustomAttributes(Type, bool) in .Net Framework returns object[],而CustomAttributeExtensions.GetCustomAttributes(this Assembly, Type) in .Net Core returns IEnumerable<Attribute>

因此您需要相应地修改代码。最简单的方法是使用.ToArray<object>(),但更好的解决方案可能是更改代码,以便它可以与IEnumerable<Attribute>一起使用。

答案 1 :(得分:8)

这适用于.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": { }
  }
}

答案 2 :(得分:5)

这对我有用:

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

    return attributes?.Title;
}

答案 3 :(得分:2)

这不是最简单的吗?

string title = Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyTitleAttribute>().Title;

就说吧。

答案 4 :(得分:1)

这就是我使用的:

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