UFO ET IT

If (Array.Length == 0)

ufoet 2021. 1. 9. 10:37
반응형

If (Array.Length == 0)


배열이 비어 있으면 ".length"를 사용하여 길이를 확인할 수없는 것 같습니다. 배열이 비어 있는지 확인하는 가장 좋은 방법은 무엇입니까?


배열의 길이를 절대적으로 확인할 수 있습니다 . 그러나 널 참조에서 그렇게하려고하면 예외가 발생합니다. 나는 그것이 당신이 겪는 일이라고 생각합니다. 하지만 다음 두 가지 모두에 대처할 수 있습니다.

if (array == null || array.Length == 0)

그것이 원인이 아니라면 문제를 보여주는 짧지 만 완전한 프로그램을 제공하십시오. 그 경우 였다 원인, 순간을 복용 그것의 가치는 당신이 "비어"컬렉션 / 현 / 대 널 참조를 이해하도록하기 위해 무엇이든.


예, 안전을 위해 아마도 다음과 같이 할 것입니다.

if(array == null || array.Length == 0)

당신이 사용할 수있는

if (array == null || array.Length == 0)

또는

if (!(array != null && array.Length >= 0))

노트!!!!! c #이 단락을 올바르게 구현하는지 확인하려면; 개체의 자식 비교로 이동하기 전에 개체를 NULL과 비교해야합니다.

C # 7.0 이상

if(!array?.Length >= 0)

.Length길이가 비어 있고 배열이 존재하는 경우 == 0을 사용할 수 있지만 null이 아닌 것이 확실합니까?


이것이 최선의 방법입니다. Array는 NET의 개체이므로 이전에 null을 확인해야합니다.


다른 사람들이 이미 제안했듯이 NullReferenceException참조가인지 먼저 확인하여 피할 수있는을 얻을 가능성이 있습니다 null. 그러나 그 수표가 실제로 정당한지 스스로에게 물어봐야합니다. 참조가 실제로있을 수 null있고 null코드에서 특별한 의미를 가지고 있기 때문에 그렇게 하시겠습니까 ? 아니면 버그를 은폐하기 위해 그렇게 하시겠습니까? 질문의 본질로 인해 후자가 될 것이라고 믿게됩니다. 어떤 경우에 당신은 정말로 코드를 깊이 조사하고 왜 그 참조가 처음에 제대로 초기화되지 않았는지 알아 내야합니다.


경우 array이며 null, derefrence하려고하면 array.Length가 발생합니다 NullReferenceException. 코드 null가에 대한 잘못된 값으로 간주 array되면이를 거부하고 호출자를 비난해야합니다. 그러한 패턴 중 하나는 다음을 던지는 것입니다 ArgumentNullException.

void MyMethod(string[] array)
{
    if (array == null) throw new ArgumentNullException(nameof(array));

    if (array.Length > 0)
    {
        // Do something with array…
    }
}

null무언가를하지 않는다는 표시 나 선택적 매개 변수로 배열 을 받아들이고 싶다면 , null이면 단순히 접근하지 않을 수 있습니다 :

void MyMethod(string[] array)
{
    if (array != null)
    {
        // Do something with array here…
    }
}

길이가 0이거나 길이가 0 일 array터치하지 않으려면 C # -6의 null 병합 연산자null 를 사용하여 동시에 둘 다 확인할 수 있습니다 .

void MyMethod(string[] array)
{
    if (array?.Length > 0)
    {
        // Do something with array…
    }
}

불필요한 길이 확인

It seems strange that you are treating the empty array as a special case. In many cases, if you, e.g., would just loop over the array anyway, there’s no need to treat the empty array as a special case. foreach (var elem in array) {«body»} will simply never execute «body» when array.Length is 0. If you are treating array == null || array.Length == 0 specially to, e.g., improve performance, you might consider leaving a comment for posterity. Otherwise, the check for Length == 0 appears superfluous.

Superfluous code makes understanding a program harder because people reading the code likely assume that each line is necessary to solve some problem or achieve correctness. If you include unnecessary code, the readers are going to spend forever trying to figure out why that line is or was necessary before deleting it ;-).


Jon Skeet answered correctly. Just remember that the order of the test in the "IF" is important. Check for the null before the length. I also prefer to put the null on the left side of the equal which is a habit I got from Java that made the code more efficient and fast… I don't think it's important in a lot of application today, but it's a good practice!

if (null == array || array.Length == 0)

Your suggested test is fine, so long as the array is intialised...

Martin.


check if the array is null first so you would avoid a null pointer exception

logic in any language: if array is null or is empty :do ....


do you mean empty or null, two different things,

if the array is instantiated but empty, then length is correct, if it has not been instantiated then test vs null

ReferenceURL : https://stackoverflow.com/questions/3213366/if-array-length-0

반응형