2009-07-28 32 views
0

我正在使用FileHelper來生成對象的屬性。下面是一個屬性的例子:.Net:有沒有更好的方法來檢查null或空字符串的對象的屬性?

<FieldOptional(), _ 
FieldTrim(TrimMode.Both)> _ 
<FieldNullValue(GetType(String), " ")> _ 
Public StoreNo As String 

正如你可以看到StoreNo要麼有一個值或「」,經營方針之一是檢查StoreNo爲空,或者什麼,如果該對象的StoreNo是空或空然後記錄不會創建。

我雖然要在類中創建一個HasValue函數來檢查對象中的StoreNo和其他屬性,但我覺得它是一個黑客。

Public Function HasValue() As Boolean 

    Dim _HasValue As Boolean = True 

    If StringHelper.IsNullOrBlank(Me.StoreNo) Then 
     _HasValue = False 
    End If 

    Return _HasValue 
End Function 

我不認爲這種方法是一個理想的解決方案。如果StoreNo被移除或更改爲其他內容,該怎麼辦?什麼是檢查對象屬性的最佳方法?

回答

3

String.IsNullOrEmpty()?

也許我失去了一些東西,這似乎太簡單了:)


而且,沒有理由寫這樣的代碼:

if String.IsNullOrEmpty(str) then 
    hasValue = false 
end 

您已經評價布爾表達式,所以直接分配的東西:

hasValue = Not String.IsNullOrEmpty(str) 
7

不確定它完全回答你的問題,但你的功能非常複雜。它可以簡化爲如下因素:

Public Function HasValue() As Boolean 
    Return Not String.IsNullOrEmpty(Me.StoreNo); 
End Function 

但後來爲什麼還要自定義功能懶得當存在於BCL String.IsNullOrEmpty

+1

`String.IsNullOrEmpty`返回 「」 假的。你也應該檢查修剪過的字符串。 – 2009-07-28 20:30:21

+0

我想檢查幾個屬性,而不只是一個。這是一個示例代碼。 – Jack 2009-07-28 20:39:24

2

您可以使用String.IsNullOrEmpty函數來測試您的字符串。

編輯

我錯過了你之前問一個更廣泛的問題。如果你想要的是一種通用類型的檢查,可以檢查多個屬性並應用於同一類型的不同對象,則可能需要考慮擴展方法。例如

public static class VariousTests 
{ 
    public static bool IsValidStoreNumber (this string value) 
    { 
    if (string.IsNullOrEmpty(value)) return false; 

    // Put additional checks here. 
    } 
} 

Note that both the class and method are declared as static. 
Note also the use of "this" in the method's parameter list, followed by the 
object type the method applies to. 

這將讓你打電話IsValidStoreNumber任何字符串變量,好像它是該字符串的方法。例如:

string test = "Some Value"; 
if (test.IsValidStoreNumber()) 
{ 
    // handle case where it is a good store number. 
} 
else 
{ 
    // handle case where it is not a good store number. 
} 

希望這是一個更加有用的答案

編輯添加的VB版本代碼

我意識到我展示時使用VB代碼,你原來的問題C#代碼。這是我的擴展方法示例的VB版本。

Imports System.Runtime.CompilerServices 

Module VariousTests 
    <Extension()> _ 
    Public Function IsValidStoreNumber (ByVal value As String) as Boolean 
    If string.IsNullOrEmpty(value) Then 
     Return False; 
    End If 

    ' Put additional checks here. 
    End Sub 
End Module 

使用:

Imports VariousTests 

Then inside a method : 

    Dim test as string = "Some Value"; 
    If test.IsValidStoreNumber() Then 
     // handle case where it is a good store number. 
    Else 
     // handle case where it is not a good store number. 
    End IF 
相關問題