How do I create a Null Object in C#

后端 未结 5 1478
南笙
南笙 2020-12-16 00:07

Martin Fowler\'s Refactoring discusses creating Null Objects to avoid lots of

if (myObject == null)

tests. What is the right way to do th

5条回答
  •  执念已碎
    2020-12-16 00:51

    The point of the Null Object pattern is that it doesn't require a null check to prevent a crash or error.

    For example if you tried to perform an operation on the Species property and it was null - it would cause an error.

    So, you shouldn't need an isNull method, just return something in the getter that won't cause the app to crash/error e.g.:

    public class Animal
    {
        public virtual string Name { get; set; }
        public virtual string Species { get; set; }
    }
    
    public sealed class NullAnimal : Animal
    {
        public override string Name
        {
            get{ return string.Empty; }
            set { ; }
        }
        public override string Species
        {
            get { return string.Empty; }
            set { ; }
        }
    }
    

提交回复
热议问题