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

前端 未结 7 1230
青春惊慌失措
青春惊慌失措 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:09

    You can't reference a property if you do not have a valid instance reference. If you want to be able to reference a property even with a null reference and not put the onus of null-checking on the caller, one way is a static method in User:

    static bool IsAuthorized(User user)
    {
        if(user!=null)
        {
            return user.IsAuthorized;
        }
        else
        {
            return false;
        }
    }
    

    Then, when you want to check your authorization, instead of:

    if(thisUser.IsAuthorized)

    Do:

    if(User.IsAuthorized(thisUser))

提交回复
热议问题