亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 C# 8 中的 System.Reflection.Metadata 獲取接口可為 null

從 C# 8 中的 System.Reflection.Metadata 獲取接口可為 null

C#
ABOUTYOU 2023-08-20 15:11:41
我目前正在制作一個工具來處理新的 C# 8 可空上下文?;旧鲜俏业捻椖康?API 審批工具。我正在使用 System.Reflection.Metadata,只是在一種情況下提取元數據時遇到問題。public class DerivedNullableBase2 : MyBase<MyBase<string?>?>{}我正在嘗試為我正在創建的 API 生成器工具獲取 C#8 可空上下文。因此,對于上面的類,會生成以下 IL:.class auto ansi nested public beforefieldinit DerivedNullableInterface2       extends [netstandard]System.Object       implements class [netstandard]System.Collections.Generic.IEnumerable`1<class [netstandard]System.Collections.Generic.IEnumerable`1<string>>,                  [netstandard]System.Collections.IEnumerable{  .interfaceimpl type class [netstandard]System.Collections.Generic.IEnumerable`1<class [netstandard]System.Collections.Generic.IEnumerable`1<string>>  .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 00 00 02 00 00 ) } // end of class DerivedNullableInterface2我想提取其中包含的 NullableAttribute 以確定通用接口的可為空上下文。我嘗試通過 TypeDefinition 和 InterfaceImplementation 獲取屬性,但似乎不存在,在這種情況下我將如何提取 NullableAttribute ?
查看完整描述

1 回答

?
皈依舞

TA貢獻1851條經驗 獲得超3個贊

以下代碼將從使用 C# 8 語法NullableAttribute中提取 a InterfaceImplementation。


using var peReader = new PEReader(File.OpenRead(Assembly.GetExecutingAssembly().Location));

var mdReader = peReader.GetMetadataReader();


foreach (var attributeHandle in mdReader.CustomAttributes)

{

? ? var attribute = mdReader.GetCustomAttribute(attributeHandle);

? ? var ctorHandle = attribute.Constructor;


? ? EntityHandle attributeTypeHandle = ctorHandle.Kind switch

? ? {

? ? ? ? HandleKind.MethodDefinition => mdReader.GetMethodDefinition((MethodDefinitionHandle)ctorHandle).GetDeclaringType(),

? ? ? ? HandleKind.MemberReference => mdReader.GetMemberReference((MemberReferenceHandle)ctorHandle).Parent,

? ? ? ? _ => throw new InvalidOperationException(),

? ? };


? ? StringHandle attributeTypeNameHandle = attributeTypeHandle.Kind switch

? ? {

? ? ? ? HandleKind.TypeDefinition => mdReader.GetTypeDefinition((TypeDefinitionHandle)attributeTypeHandle).Name,

? ? ? ? HandleKind.TypeReference => mdReader.GetTypeReference((TypeReferenceHandle)attributeTypeHandle).Name,

? ? ? ? _ => throw new InvalidOperationException(),

? ? };


? ? if (mdReader.StringComparer.Equals(attributeTypeNameHandle, "NullableAttribute"))

? ? {

? ? ? ? Console.WriteLine(attribute.Parent.Kind);

? ? }

}


查看完整回答
反對 回復 2023-08-20
  • 1 回答
  • 0 關注
  • 192 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號