Pir*_*ber 13 .net c# .net-core
我知道.NET Core的替代品Assembly.GetExecutingAssembly()是typeof(MyType).GetTypeInfo().Assembly,但是替换的是什么
Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false)
Run Code Online (Sandbox Code Playgroud)
我已经尝试在组装之后附加代码的最后一位用于提到的第一个解决方案,如下所示:
typeof(VersionInfo).GetTypeInfo().Assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute));
Run Code Online (Sandbox Code Playgroud)
但它给了我一个"不能隐式转换为object []的消息.
更新: 是的,正如下面的评论所示,我认为它与输出类型相关联.
这是代码片段,我只是想将其更改为与.Net Core兼容:
public class VersionInfo
{
public static string AssemlyTitle
{
get
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
// More code follows
Run Code Online (Sandbox Code Playgroud)
我已经尝试将其更改为使用CustomAttributeExtensions.GetCustomAttributes(但我目前还不了解c#,知道如何实现与上面相同的代码.关于MemberInfo和Type之类的东西我还是混淆了.非常感谢任何帮助!
我怀疑问题出在你没有显示的代码中:你在哪里使用结果GetCustomAttributes().那是因为Assembly.GetCustomAttributes(Type, bool).Net Framework返回object[],而CustomAttributeExtensions.GetCustomAttributes(this Assembly, Type).Net Core返回IEnumerable<Attribute>.
所以你需要相应地修改你的代码.最简单的方法是使用.ToArray<object>(),但更好的解决方案可能是更改代码以便它可以使用IEnumerable<Attribute>.
这适用于.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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
AssemblyInfo.cs中
using System.Reflection;
[assembly: AssemblyTitle("My Assembly Title")]
Run Code Online (Sandbox Code Playgroud)
project.json
{
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
},
"System.Runtime": "4.1.0"
},
"frameworks": {
"netcoreapp1.0": { }
}
}
Run Code Online (Sandbox Code Playgroud)
小智 7
这不是最简单的吗?
string title = Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyTitleAttribute>().Title;
Run Code Online (Sandbox Code Playgroud)
只是在说。
这对我有用:
public static string GetAppTitle()
{
AssemblyTitleAttribute attributes = (AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false);
return attributes?.Title;
}
Run Code Online (Sandbox Code Playgroud)