如何判断方法的返回类型是否可以为空?
项目设置<Nullable>enable</Nullable>
是活动的.
一些示例(所有方法都是类型Task
或Task<T>
)
public sealed class Dto
{
public int Test { get; set; }
}
public sealed class Dto3
{
public int? Test { get; set; }
}
public async Task<Dto?> GetSomething()
{
// This should be found as "Nullable enabled" as the `?` is set.
}
public async Task<Dto3> GetSomething2()
{
// This should not be found as "Nullable enabled" as the `?` is missing.
}
public async Task<List<Dto>> GetSomething3()
{
// This should not be found as "Nullable enabled" as the `?` is missing
// (And the list must be initialized anyways thanks to nullable context).
}
public async Task<List<Dto?>> GetSomething3()
{
// This should not be found as "Nullable enabled" as the `?` is missing in the first generic type after `Task`.
}
我已经有了遍历搜索名称空间中的类和方法的代码,如下所示:
var assembly = Assembly.GetAssembly(typeof(ISomethingService));
if (assembly is null)
{
throw new InvalidOperationException("This should never happen");
}
var classes = assembly.GetTypes().Where(type =>
(type.Namespace == typeof(ISomethingService).Namespace || type.Namespace == typeof(ISomethingService2).Namespace) && type.IsInterface);
foreach (var @class in classes)
{
var methods = @class.GetMethods();
foreach (var method in methods)
{
foreach (var genericType in method.ReturnType.GenericTypeArguments)
{
if (IsNullable(genericType))
{
Console.WriteLine($"Return type of method {@class.Name}.{method.Name} is nullable: {genericType.Name}");
}
}
}
}
可为空的判断目前是这样实现的,但不能按预期工作:
private static bool IsNullable<T>(T obj)
{
if (obj == null) return true; // obvious
Type type = typeof(T);
if (!type.IsValueType) return true; // ref-type
if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T>
return false; // value-type
}
有没有办法达到想要的结果(例如,如果在Task<T>
之后的第一级(泛型)上设置了?
,则只有IsNullable
是true
)?