Is there a way to have a C# class handle its own null reference exceptions

前端 未结 7 1147
青春惊慌失措
青春惊慌失措 2021-02-05 05:05

Question

I\'d like to have a class that is able to handle a null reference of itself. How can I do this? Extension methods are the only way I can think

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-05 05:18

    How about a proper Object Oriented solution? This is exactly what the Null Object design pattern is for.

    You could extract an IUser interface, have your User object implement this interface, and then create a NullUser object (that also implements IUser) and always returns false on the IsAuthorized property.

    Now, modify the consuming code to depend on IUser rather than User. The client code will no longer need a null check.

    Code sample below:

    public interface IUser
    {
        // ... other required User method/property signatures
    
        bool IsAuthorized { get; }
    }
    
    public class User : IUser
    {
        // other method/property implementations
    
        public bool IsAuthorized
        {
            get { // implementation logic here }
        }
    }
    
    public class NullUser : IUser
    {
        public bool IsAuthorized
        {
            get { return false; }
        }
    }
    

    Now, your code will return an IUser rather than a User and client code will only depend on IUser:

    public IUser GetUser()
    {
        if (condition)
        {
            return new NullUser(); // never return null anymore, replace with NullUser instead
        }
        return new User(...);
    }
    

提交回复
热议问题