Programing

foreach 루프에서 null 확인

crosscheck 2020. 10. 23. 07:36
반응형

foreach 루프에서 null 확인


다음을 수행하는 더 좋은 방법이 있습니까?
루프를 진행하기 전에 file.Headers에서 null이 발생하는지 확인해야합니다.

if (file.Headers != null)
{
  foreach (var h in file.Headers)
  {
   //set lots of properties & some other stuff
  }
}

요컨대 내 코드에서 발생하는 들여 쓰기 수준으로 인해 if 내부에 foreach를 작성하는 것이 약간 추악 해 보입니다.

평가할 것입니다

foreach(var h in (file.Headers != null))
{
  //do stuff
}

가능한?


룬의 제안에 약간의 외형을 추가 한 것처럼 자신 만의 확장 방법을 만들 수 있습니다.

public static IEnumerable<T> OrEmptyIfNull<T>(this IEnumerable<T> source)
{
    return source ?? Enumerable.Empty<T>();
}

그런 다음 다음과 같이 작성할 수 있습니다.

foreach (var header in file.Headers.OrEmptyIfNull())
{
}

취향에 따라 이름 변경 :)


file.Headers의 요소 유형이 T라고 가정하면 다음을 수행 할 수 있습니다.

foreach(var header in file.Headers ?? Enumerable.Empty<T>()){
  //do stuff
}

file.Headers가 null 인 경우 T의 빈 열거 형이 생성됩니다. 파일 유형이 내가 소유 한 유형 인 경우 Headers대신 getter를 변경하는 것이 좋습니다. null는 알 수없는 값이므로 가능하면 null을 "I know there are no elements"로 사용하는 대신 null을 실제로 (/ 원래) "I do n't know if any elements"로 해석해야 할 때 빈 집합을 사용하여 표시합니다. 세트에 요소가 없다는 것을 알고 있습니다. null 검사를 자주 수행 할 필요가 없기 때문에 더 건조 해집니다.

Jons 제안에 대한 후속 조치로 편집 하면 위의 코드를 다음과 같이 변경하는 확장 메서드를 만들 수도 있습니다.

foreach(var header in file.Headers.OrEmptyIfNull()){
  //do stuff
}

getter를 변경할 수없는 경우에는 오퍼레이션에 이름 (OrEmptyIfNull)을 부여하여 의도를보다 명확하게 표현하므로 제가 선호하는 방법입니다.

위에서 언급 한 확장 방법은 옵티마이 저가 감지 할 수없는 특정 최적화를 만들 수 있습니다. 특히 메서드 오버로딩을 사용하여 IList와 관련된 항목을 제거 할 수 있습니다.

public static IList<T> OrEmptyIfNull<T>(this IList<T> source)
{
    return source ?? Array.Empty<T>();
}

솔직히, 나는 조언한다 : 그냥 null시험을 빨아 라 . null테스트는 단지brfalse 또는 brfalse.s; 다른 모든 (불필요한 시험, 과제, 여분의 메소드 호출, 훨씬 더 많은 작업을 포함하는 것입니다 GetEnumerator(), MoveNext(), Dispose()반복자에, 등).

if테스트는 간단하고 분명하고 효율적입니다.


반복 전의 "if"는 괜찮습니다. 이러한 "예쁜"의미 체계 중 일부는 코드의 가독성을 떨어 뜨릴 수 있습니다.

어쨌든 들여 쓰기로 인해 방해가되는 경우 다음을 확인할 if를 변경할 수 있습니다.

if(file.Headers == null)  
   return;

headers 속성에 참 값이있을 때만 foreach 루프를 얻을 수 있습니다.

내가 생각할 수있는 또 다른 옵션은 foreach 루프 내에서 null 통합 연산자를 사용하고 null 검사를 완전히 피하는 것입니다. 견본:

List<int> collection = new List<int>();
collection = null;
foreach (var i in collection ?? Enumerable.Empty<int>())
{
    //your code here
}

(컬렉션을 실제 개체 / 유형으로 대체)


사용 널 조건 연산자 빠르게 표준 foreach 루프에 비해 작동하고 foreach는 ()를.
하지만 컬렉션을 List로 캐스팅해야합니다.

   listOfItems?.ForEach(item => // ... );

이 시나리오에 대해 멋진 작은 확장 방법을 사용하고 있습니다.

  public static class Extensions
  {
    public static IList<T> EnsureNotNull<T>(this IList<T> list)
    {
      return list ?? new List<T>();
    }
  }

Headers가 목록 유형이므로 다음을 수행 할 수 있습니다.

foreach(var h in (file.Headers.EnsureNotNull()))
{
  //do stuff
}

For some cases I'd prefer slightly another, generic variant, assuming that, as a rule, default collection constructors return empty instances.

It would be better to name this method NewIfDefault. It can be useful not only for collections, so type constraint IEnumerable<T> is maybe redundant.

public static TCollection EmptyIfDefault<TCollection, T>(this TCollection collection)
        where TCollection: class, IEnumerable<T>, new()
    {
        return collection ?? new TCollection();
    }

참고URL : https://stackoverflow.com/questions/11734380/check-for-null-in-foreach-loop

반응형