![](/img/trans.png)
[英]How to allow nullable generic type in C# 8 as a return type for a method?
[英]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...??
我嘗試使用NullabilityInfoContext
但Create
方法接受PropertyInfo
、 ParameterInfo
、 FieldInfo
、 EventInfo
這在這里並沒有真正幫助,或者我無法弄清楚如何。
這里的解決方案也只接受PropertyInfo
、 FieldInfo
和EventInfo
我還嘗試觀察 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.