簡體   English   中英

C# 使用反射從方法返回類型的泛型參數中檢測可為空的引用類型

[英]C# detect nullable reference type from generic argument of method's return type using reflection

我在 .net-6/C#9 中有這個簡單的接口,並啟用了可空引用類型:

public interface IMyInterface
{
    Task<MyModel?> GetMyModel();
}

我如何通過反射檢測到方法返回類型的泛型參數MyModel實際上被聲明為可為 null 的引用類型MyModel?

我試過的...

typeof(IMyInterface).GetMethods()[0].ReturnType...??

我嘗試使用NullabilityInfoContextCreate方法接受PropertyInfoParameterInfoFieldInfoEventInfo這在這里並沒有真正幫助,或者我無法弄清楚如何。

這里的解決方案也只接受PropertyInfoFieldInfoEventInfo

我還嘗試觀察 method.ReturnType.GenericTypeArguments method.ReturnType.GenericTypeArguments[0]的屬性,但返回Task<MyModel>Task<MyModel?>的方法沒有區別

自定義屬性

MethodInfo.ReturnParameter用於NullabilityInfoContext

Type type = typeof(IMyInterface);
var methodInfo = type.GetMethod(nameof(IMyInterface.GetMyModel));

NullabilityInfoContext context = new();
var nullabilityInfo = context.Create(methodInfo.ReturnParameter); // return type
var genericTypeArguments = nullabilityInfo.GenericTypeArguments;
var myModelNullabilityInfo = genericTypeArguments.First(); // nullability info for generic argument of Task
Console.WriteLine(myModelNullabilityInfo.ReadState);    // Nullable
Console.WriteLine(myModelNullabilityInfo.WriteState);   // Nullable

要分析可為 null 的屬性,可以使用methodInfo.ReturnTypeCustomAttributes.GetCustomAttributes(true)

暫無
暫無

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

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