Best practice when using C# 8.0 nullable reference types with deserialization?

后端 未结 3 1967
长发绾君心
长发绾君心 2021-01-15 03:36

I am trying C# 8.0 out, and I want to enable the null reference checking for the entire project. I am hoping I can improve my code design, and without disabling the nullabil

3条回答
  •  我在风中等你
    2021-01-15 04:08

    While certainly highlighted due to non-nullable defaults in C# 8, this is really a common 'circular dependency' problem that has always existed with interdependent construction.

    As you found, one standard solution is to use a restricted setter. With C# 8, you may want to use a 'null-forgiving' null! during deserialization of the object graph - allowing you to differentiate an unconstructed set from a valid empty set, and minimize allocation.

    Example:

    class Person
    {
        internal Person(string name, IReadOnlyList friends)
        {
            Name = name; Friends = friends
        }
    
        public string Name { get; }
        public IReadOnlyList Friends {get; internal set;}
    }
    
    class SerializedPerson { ... }
    
    IEnumerable LoadPeople(string path)
    {
        var serializedPeople = LoadFromFile(path);
    
        // Note the use of null!
        var people = serializedPeople.Select(p => new Person(p.Name, null!));
    
        foreach(var person in people)
        {
            person.Friends = GetFriends(person, people, serializedPeople);
        }
    
        return people;
    }
    

提交回复
热议问题