【问题标题】:Determine Nullability Of A Reference Type in C# Using Reflection [duplicate]使用反射确定 C# 中引用类型的可空性 [重复]
【发布时间】: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 是否可以为空(即使用可空运算符 ? 定义)。

【问题讨论】:

标签: c# .net .net-core c#-8.0 nullable-reference-types


【解决方案1】:

我想出了完整的解决方案。我们需要检查属性和类上的自定义属性。


...


private const byte NonNullableContextValue = 1;
private const byte NullableContextValue = 2;

public IEnumerable<string> GetNullableProperties(Type type)
{
    foreach (var property in type.GetProperties())
    {
       var isNullable = property.PropertyType.IsValueType
           ? Nullable.GetUnderlyingType(property.PropertyType) != null;
           : IsReferenceTypePropertyNullable(property);

       if (isNullable)
       {
           nullableProperties.Add(property.propertyType.Name)
       }
    }
    return nullableProperties;
}

private function bool IsReferenceTypePropertyNullable(PropertyInfo property)
{
    var classNullableContextAttribute = property.DeclaringType.CustomerProperties
       .FirstOrDefault(c => c.AttributeType.Name == "NullableContextAttribute")

    var classNullableContext = classNullableContextAttribute
        ?.ConstructorArguments
        .First(ca => ca.ArgumentType.Name == "Byte")
        .Value;

    // EDIT: This logic is not correct for nullable generic types
    var propertyNullableContext = property.CustomAttributes
        .FirstOrDefault(c => c.AttributeType.Name == "NullableAttribute")
        ?.ConstructorArguments
        .First(ca => ca.ArgumentType.Name == "Byte")
        .Value;

    // If the property does not have the nullable attribute then it's 
    // nullability is determined by the declaring class 
    propertyNullableContext ??= classNullableContext;

    // If NullableContextAttribute on class is not set and the property
    // does not have the NullableAttribute, then the proeprty is non nullable
    if (propertyNullableContext == null)
    {
         return true;
    }

    // nullableContext == 0 means context is null oblivious (Ex. Pre C#8)
    // nullableContext == 1 means not nullable
    // nullableContext == 2 means nullable
    switch (propertyNullableContext)
    {
        case NonNullableContextValue:
            return false;
        case NullableContextValue:
            return true;
        default:
            throw new Exception("My error message");
    }
}

以下是有关可为空的上下文值的一些信息:https://www.postsharp.net/blog/post/PostSharp-internals-handling-csharp-8-nullable-reference-types

【讨论】:

【解决方案2】:

您需要检查属性本身而不是属性类型中的自定义属性。

    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.CustomAttributes
                   .FirstOrDefault(a => a.AttributeType.Name == "NullableAttribute");
                isNullable = nullableAttribute == null;
            }

            if (isNullable)
            {
                nullableProperties.Add(property.Name);
            }
        }
        return nullableProperties;
    }

此外,如果属性可以为空,则未定义此属性。如果属性不可为空,则该属性存在。

【讨论】:

  • 谢谢维克多。我认为最后一句话应该倒过来。此外,这个问题还有更多。我还需要查看类的自定义属性。我在下面发布了一个完整的解决方案。
猜你喜欢
  • 1970-01-01
  • 2017-04-24
  • 1970-01-01
  • 2011-09-15
  • 1970-01-01
  • 2010-10-25
  • 1970-01-01
  • 1970-01-01
  • 2010-11-14
相关资源
最近更新 更多