Is it acceptable to use exceptions instead of verbose null-checks?

前端 未结 9 2447
刺人心
刺人心 2020-12-28 21:51

I recenly encountered this problem in a project: There\'s a chain of nested objects, e.g.: class A contains an instance variable of class B, which in turns has an instance v

9条回答
  •  悲哀的现实
    2020-12-28 22:21

    I agree with the other answers that this should not need to be done, but if you must here is an option:

    You could create an enumerator method once such as:

        public IEnumerable GetSubProperties(ClassA A)
        {
            yield return A;
            yield return A.B;
            yield return A.B.C;
            ...
            yield return A.B.C...Z;
        }
    

    And then use it like:

        var subProperties = GetSubProperties(parentObject);
        if(SubProperties.All(p => p != null))
        {
           SubProperties.Last().DoSomething();
        }
    

    The enumerator will be lazily evaluated leading to no exceptions.

提交回复
热议问题