簡體   English   中英

GetCustomAttribute 在 .NET5 上的運行時返回 null

[英]GetCustomAttribute returns null in runtime on .NET5

我有一個加載程序集並按屬性對數據進行分類的代碼。

我正在嘗試獲取實際的 CustomAttribute 對象。 在網絡框架上調試期間,代碼返回一個值。 在 .Net5 上運行代碼返回 null

在對文檔進行一些挖掘后進行編輯

.NET Framework 2.0 版提供了一個新的加載上下文,即僅反射上下文,可用於檢查無法加載執行的代碼。

https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/accessing-custom-attributes

編輯 #2原因是我試圖在運行時獲取對象,並且如上面的文檔引用中所述,無法加載該屬性以及任何其他僅運行時反射的上下文,並且該方法返回 null。

除了使用 system.reflection 在運行時獲取實際屬性對象之外,還有其他解決方案嗎?

字典初始化

        var ass = Assembly.LoadFile(Path.GetFullPath("MyInterface.dll"));
        var asss = Assembly.GetExecutingAssembly();
        var apiInterfaces = ass.DefinedTypes.Where(x => x.IsInterface && x.CustomAttributes != null && x.CustomAttributes.Any(z => z.AttributeType.FullName != null && z.AttributeType.FullName.Equals(typeof(ApiInterfaceDescriptorAttribute).FullName)));
        

屬性:

[AttributeUsage(AttributeTargets.Interface)]
public class ApiInterfaceDescriptorAttribute : Attribute
{
    public string ApiUsageName { get; }

    public ApiInterfaceDescriptorAttribute(string apiUsageName)
    {
        ApiUsageName = apiUsageName;
    }
}

示例界面

[ApiInterfaceDescriptor("powercontrol")]
public interface IMyInterface 
{
   [ApiMethodDescriptor(ApiExposureLevel.Basic, "a-method...")]
    void SomeMethod();
}

獲取屬性的試用

public class ApiDetector
{
    private Dictionary<Type, List<MethodInfo>> _apiDictionary = new Dictionary<Type, List<MethodInfo>>();
    public void LoadApiElements()
    {
        var apiKeyDesriptor = key.GetCustomAttribute(typeof(ApiInterfaceDescriptorAttribute)) as ApiInterfaceDescriptorAttribute;
            _apiDetector.Add(new ApiDataObjectDescriptor { Name = key.Name, ApiUsageName = apiKeyDesriptor?.ApiUsageName, Type = key });
    }

}

當我在本地運行此代碼時,我得到了實例: 在此處輸入圖片說明

在 .Net5 遠程機器上運行代碼返回 null:

在此處輸入圖片說明

歡迎任何幫助。 先謝謝了!

根本原因是對 Assembly.LoadFile 的調用。 此方法始終將指定的程序集加載到其自己的 AssemblyLoadContext 中。 (更多關於程序集加載上下文)。

這意味着您已將程序集加載到 LoadFile 加載上下文(一個副本)中,並且我從您的主代碼中直接引用了它,這會將它加載到默認加載上下文(第二個副本)中。 雖然程序集文件完全相同,但對於運行時來說,這兩個副本是不同的程序集,兩者中的所有類型都將被視為不同的類型。

將程序集加載方法更改為:

Assembly.GetAssembly(typeof(MyType));

已經解決了問題。

感謝 Microsoft 支持團隊的 vitek-karas。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM