How to verify generic return type in BuildEligibility for async methods? #318
-
New to metalama, so this might be obvious but cannot find any help through the docs. I would like to check something like builder.MustSatisfy(m =>
m.ReturnType.Is(typeof(Task<ServiceResponse>)) ||
m.ReturnType.Is(typeof(Task<ServiceResponse<>>)),
m => $"{m} must return Task<ServiceResponse> or Task<ServiceResponse<T>>"); but this obviously wont work since I tried the following, but it won't work due since runtime reflection cannot be used at compile time. builder.MustSatisfy(m =>
m.ReturnType.Is(typeof(Task<ServiceResponse>)) ||
m.ReturnType.ToType().GenericTypeArguments[0].GetGenericTypeDefinition() == typeof(ServiceResponse<>),
m => $"{m} must return Task<ServiceResponse> or Task<ServiceResponse<T>>"); Resorted to the following solution, which works, but there must be a better way.. builder.MustSatisfy(m =>
m.ReturnType.ToString()!.Contains("ServiceResponse"),
m => $"{m} must return Task<ServiceResponse> or Task<ServiceResponse<T>>"); Please help me understand how I will properly test for a generic return type for async methods. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You can use builder.ReturnType().MustSatisfy(
type => type.Is(typeof(Task<ServiceResponse>)) ||
(type.Is(typeof(Task<>), ConversionKind.TypeDefinition) &&
((INamedType)type).TypeArguments.Single().Is(typeof(ServiceResponse<>), ConversionKind.TypeDefinition)),
t => $"{t} must be Task<ServiceResponse> or Task<ServiceResponse<T>>"); (I also changed the code to use Another option is to use builder.ReturnType().MustSatisfy(
type =>
{
var asyncInfo = type.GetAsyncInfo();
return asyncInfo.IsAwaitable &&
(asyncInfo.ResultType.Is(typeof(ServiceResponse)) ||
asyncInfo.ResultType.Is(typeof(ServiceResponse<>), ConversionKind.TypeDefinition));
}, t => $"{t} must be Task<ServiceResponse> or Task<ServiceResponse<T>>"); |
Beta Was this translation helpful? Give feedback.
You can use
Is
withConversionKind.TypeDefinition
for this:(I also changed the code to use
builder.ReturnType()
, but that's not necessary.)Another option is to use
GetAsyncInfo()
, which will work for any awaitable type (likeValueTask<T>
):