我有一个使用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
是否可空(即是否使用可空运算符 ?
定义)?