.net - 如何使用反射判断对象的类型是否为Nullable <T>?

标签 .net reflection nullable

如果我有Type,是否有一些简单的方法可以使用Reflection来表示它代表可为空的值类型?理想情况是比以下方法更干净(并且更正确)的东西:

static bool IsNullable(Type type)
{
    return type.IsValueType && type.Name.StartsWith("Nullable");
}

最佳答案

type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)

您可能还会发现Nullable.GetUnderlyingType(Type nullableType)有用,可以轻松获取传入的Ttypeof(Nullable<T>)

关于.net - 如何使用反射判断对象的类型是否为Nullable <T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3865021/

相关文章:

c# - 如何修复此错误 {"Length cannot be less than zero.\r\nParameter name: length"} 在我的代码中的 c# 我正在使用带有 indexofany 的子字符串

c# - 获取创建对象的类的名称

java - 在 Kotlin 中,GSON.fromJson(...) 如何设法改变现有对象的只读字段?

null - 没有NULL的类C语言?

android - 各种问题@NonNull、@NotNull 和@ParametersAreNonnullByDefault

c# - Rx .net Subscribe() 和 EventPattern 奇怪

.net - 收到 500 内部服务器错误

java - 在 java 中,如何序列化未标记为 Serializable 的类?

c# - Xamarin.Forms(可为空)DatePicker : Workaround for missing OK and cancel events

c# - Dns.GetHostAddresses 真的取回所有已注册的 IP 吗?