首页 > 解决方案 > 当我们更改第二个字段的可空性时,为什么会更改第一个字段的可空性 CustomAttribute

问题描述

我对.net中的可空(我认为)类型有奇怪的问题

我将我的问题简化为这段代码:

using System.Linq;

namespace CustomAttribute
{
    class Program
    {
        static void Main(string[] args)
        {
            var person1_firstName_Props = typeof(Person1).GetProperties().Single(x => x.Name == nameof(Person1.FirstName));
            var person2_firstName_Props = typeof(Person2).GetProperties().Single(x => x.Name == nameof(Person2.FirstName));

            var person1_firstName_CustomAttributes = person1_firstName_Props.CustomAttributes;
            var person2_firstName_CustomAttributes = person2_firstName_Props.CustomAttributes;

            // why person2_firstName_CustomAttributes is empty? if we changed nullability of LastName ?
        }
    }

    class Person1
    {
        public string? FirstName { get; set; } = null!;
        public string LastName { get; set; } = null!;
    }

    class Person2
    {
        public string? FirstName { get; set; } = null!;
        public string? LastName { get; set; } = null!;
    }
}

问题是为什么当我更改姓氏字段功能时(我添加了“?”可为空的),与名字字段(其属性/属性)相关的更改。该问题出现在 c# 8 和早期版本中。

标签: c#nullable-reference-types

解决方案


推荐阅读