如何获得AssemblyTitle?

问题描述 投票:11回答:5

我知道Assembly.GetExecutingAssembly()的.NET核心替代品是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之类的东西我还是混淆了。非常感谢任何帮助!

c# .net .net-core
5个回答
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>一起使用。


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": { }
  }
}

5
投票

这对我有用:

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

    return attributes?.Title;
}

2
投票

这不是最简单的吗?

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

只是在说。


1
投票

这是我用的:

private string GetApplicationTitle => ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false))?.Title ?? "Unknown Title";
© www.soinside.com 2019 - 2024. All rights reserved.