Home Будинок » » Dot Net Чистий Dot

5 Wrong ways to check empty strings 5 Неправильний шлях перевірити порожніми рядками

It is one of the common mistake that people compare a string with “” or String.Empty in VB.Net or C# to find its empty. Вона є однією з загальних помилки, які люди порівняти рядок з "" або String.Empty в VB.Net или C #, щоб знайти його порожнім. Here are few examples. Ось кілька прикладів.

// C# Wrong Ways / / C # Невірний Шляхи

  1. if ( s == “” ) якщо (S == "")
  2. if ( s == string.Empty ) якщо (S == string.Empty)
  3. if ( s.Equals(””) ) якщо (s.Equals ( ""))
  4. if ( s.Equals ( String.Empty) якщо (s.Equals (String.Empty)
  5. if ( string.Equals(s,””) якщо (string.Equals (S, "")
  6. if ( string.Equals ( s,String.Empty )) якщо (string.Equals (S, String.Empty))

So what's the correct way to do it ? Так що, як правильно це зробити? Check for length too. Перевірити довжину теж.

// [ C# ] Correct Way / / [C #] Правильний шлях

if ( s.Length == 0 ) якщо (s.Length == 0)

This is in continuation of our last post on Це в продовження нашої останнього на пост Check for length too when you check for null strings in VB.Net and C# Перевірити довжину теж коли ви перевіряєте на нуль рядків у VB.Net і C #

Read below for the right approach. Читайте нижче, правильний підхід.

  • Ryan Heaney Райан Heaney , March 27, 2008: 27 березня 2008 року:

    I agree with Shahar. Я згоден з Гашшахар. string.IsNullOrEmpty is the best, managed way to test. string.IsNullOrEmpty є кращим, управляє спосіб тестування. It's static and guaranteed not to throw a NullReferenceException. Це статична і гарантувати не кинути NullReferenceException. You can't say that about .Length. Ви не можете сказати, що о. Довжина.

    If you look at the disassembly of string.IsNullOrEmpty you will see what it does. Якщо ви подивитеся на розбирання string.IsNullOrEmpty ви побачите, що вона робить.
    .method public hidebysig static bool IsNullOrEmpty(string 'value') cil managed . Методі громадських hidebysig статичних BOOL IsNullOrEmpty (рядок 'значення') КСС вдалося
    { (
    .maxstack 8 . Maxstack 8
    L_0000: ldarg.0 L_0000: ldarg.0
    L_0001: brfalse.s L_000d L_0001: brfalse.s L_000d
    L_0003: ldarg.0 L_0003: ldarg.0
    L_0004: callvirt instance int32 System.String::get_Length() L_0004: callvirt інстанції int32 System.String:: get_Length ()
    L_0009: ldc.i4.0 L_0009: ldc.i4.0
    L_000a: ceq L_000a: CEQ
    L_000c: ret L_000c: у відставці
    L_000d: ldc.i4.1 L_000d: ldc.i4.1
    L_000e: ret L_000e: у відставці
    } )

    This translates to (C#): Це призводить до (C #):
    public static bool IsNullOrEmpty(string value) громадськості статичної BOOL IsNullOrEmpty (рядкові значення)
    { (
    if (value != null) якщо (значення! = NULL)
    { (
    return (value.Length == 0); повернення (value.Length == 0);
    } )
    return true; повернутися вірно;
    } )

    Now while you can perform this operation on your own, the whole point of the .NET Framework is the fact that this is managed code. Тепер Ви можете виконати цю дію на свій власний, то все и дело платформи. NET Framework є той факт, що це вдалося код. If for some reason Microsoft decides to change the implementation of the string class such that there is another case in which it is empty, it would change its implementation here. Якщо з якихось причин Microsoft вирішить змінити здійснення рядок класу такі, що є ще один випадок, коли вона порожня, вона призведе до зміни її здійсненню тут. And you would never have to worry about your code breaking due to an underlying change. І ви ніколи не доведеться турбуватися про ваш код розірвати зв'язку з основоположних змін.

    So, in short, use string.IsNullOrEmpty(). Отже, коротше кажучи, використовувати string.IsNullOrEmpty ().

SMS підпискаPrint This Post

Posted on 6th April 2008 by Опубліковано 6 квітня 2008 року Ashish Mohta Ashish Mohta , A tech blogger who writes about solving day to day problems of people who use computer. , А тек блогери, який пише про вирішення повсякденних проблем людей, які використовують комп'ютер. He also writes on How to use the applications like Office, PC tips, Online tools,Browsers and more. All posts by Він також пише про те, як використовувати у програмах, як управління, PC поради, онлайн інструменти, браузери та багато чого іншого. Всі посади Ashish Mohta Ashish Mohta | Connect with me @ | Зв'язатися зі мною @ Twitter Щебетати | | Linkedin LinkedIn | | Facebook Facebook | | Stumble Stumble | Need more help? | Потрібна допомога? Ask your Questions at our Задайте свої питання на нашому Support Center Центр підтримки

Leave your response! Залиште свій відгук!

Be nice. Бути красивим. Keep it clean. Тримайте його в чистоті. Stay on topic. Перебування на темі. No spam. Не спам.

Ім'я

You can use these tags: Ви можете використовувати ці теги:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Translate to EnglishÜbersetzen Sie zum Deutsch/GermanΜεταφράστε στα ελληνικά/GreekПереведите к русскому/RussianOversetter til Norsk/NorwegianÖversätta till Svensk/Swedishहिन्दी अनुवाद करने के लिए/Hindi
Tradueix al català/CatalanTulkot uz latviešu/LatvianPreložiť do slovenčiny/SlovakVertaal aan het Nederlands/Dutchترجمة الى العربية/ArabicTraduzca al Español/SpanishTraduisez au Français/French
Traduca ad Italiano/ItalianTraduza ao Português/Portuguese日本語に翻訳しなさい /Japanese한국어에게 번역하십시오/Korean中文翻译/Chinese Simplified中文翻译/Chinese TraditionalПереклад на українську/Ukrainian