【发布时间】:2020-05-06 02:14:14
【问题描述】:
我有使用 C#-8 和可空类型的 .NET Core 项目。
我有以下课程
public class MyClass
{
public int? NullableInt { get; private set; }
public string? NullableString { get; private set; }
public string NonNullableString { get; private set; }
public MySubClass? MyNullableSubClass { get; private set; }
}
我需要能够遍历类的所有属性并确定哪些属性可以为空。
所以我的代码看起来像这样
public IEnumerable<string> GetNullableProperties(Type type)
{
var nullableProperties = new List<string>();
foreach (var property in type.GetProperties())
{
var isNullable = false;
if (property.PropertyType.IsValueType)
{
isNullable = Nullable.GetUnderlyingType(property.PropertyType) != null;
} else {
var nullableAttribute = property.PropertyType.CustomAttributes
.FirstOrDefault(a => a.AttributeType.Name == "NullableAttribute");
isNullable = nullableAttribute != null;
}
if (isNullable)
{
nullableProperties.Add(property.propertyType.Name)
}
}
return nullableProperties;
}
将MyClass 的类型传递给此方法会返回["NullableInt", "NullableString", "NonNullableString", "MyNullableSubClass"]。
但是,预期的返回值是["NullableInt", "NullableString", "MyNullableSubClass"]。
NonNullableString属性之所以确定为可空,是因为它上面有Nullable属性。
我的理解是,在判断一个引用类型是否可以为空的时候,需要检查它是否有Nullable属性。但是,字符串类型似乎并非如此。似乎所有字符串都定义了可为空的属性。有没有办法确定 string 是否可以为空(即使用可空运算符 ? 定义)。
【问题讨论】:
-
这比此处或链接问题涵盖的任何答案都复杂得多。一个名为 Namotion.Reflection 的库有一个看似万无一失的实现。
标签: c# .net .net-core c#-8.0 nullable-reference-types