Как получить AssemblyTitle?
Я знаю замену.NET Core для Assembly.GetExecutingAssembly()
является typeof(MyType).GetTypeInfo().Assembly
, но как насчет замены
Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false)
Я попытался добавить последний бит кода после сборки для первого решения, упомянутого так:
typeof(VersionInfo).GetTypeInfo().Assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute));
но это дает мне сообщение "Не могу неявно преобразовать в объект [] сообщение.
ОБНОВЛЕНИЕ: Да, как показывают комментарии ниже, я считаю, что это связано с типом вывода.
Вот фрагмент кода, и я просто пытаюсь изменить его, чтобы он был совместим с.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 ответов
Я подозреваю, что проблема в коде, который вы не показали: где вы используете результат GetCustomAttributes()
, Это потому что Assembly.GetCustomAttributes(Type, bool)
в.Net Framework возвращаетсяobject[]
, в то время как CustomAttributeExtensions.GetCustomAttributes(this Assembly, Type)
в.Net Core возвращаетсяIEnumerable<Attribute>
,
Поэтому вам нужно соответствующим образом изменить свой код. Самый простой способ будет использовать .ToArray<object>()
, но лучшим решением может быть изменение вашего кода, чтобы он мог работать с IEnumerable<Attribute>
,
Разве это не будет самым простым?
string title = Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyTitleAttribute>().Title;
Просто говорю.
Это работает для меня в.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;
}
Это то, что я использую:
private string GetApplicationTitle => ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false))?.Title ?? "Unknown Title";