2012-07-07 27 views
0

我有以下幾點:如何使用get從C#類返回布爾值?

public class Content { 
    public string PartitionKey { get; set; } 
    public string RowKey { get; set; } 
    ... 
} 

public class ContentViewModel 
    { 
     public string RowKey { get; set; } 
     public Content Content { get; set; } 
     public Boolean UseRowKey { } 

    } 

有人能告訴我怎麼可以編碼爲UseRowKey到只讀,併爲它如果Content.RowKey第一個字符是「X」返回true。

+2

請閱讀關於MSDN上的屬性和字符串操作的一些信息,以便您更好地理解您要做的事情。 – Chris 2012-07-07 13:35:13

回答

1

如何使用獲得從C#類返回一個布爾值?

你不能因爲類沒有返回值,只有方法有(和屬性 - get方法是方法的特例)。

現在:

誰能告訴我怎麼可以編碼爲UseRowKey爲只讀,併爲它返回 真,如果Content.RowKey第一個字符是「X」

但是,這不是「從班級返回布爾值」,你知道。

public bool UseRowKey { get { return RowKey.StartsWith("X"); }} 

(未經測試,您可能需要調試)

只讀:不提供一套。 第一個字符X:編程。

3

您可以使用此代碼:

public Boolean UseRowKey { 
    get { 
     return Content != null 
      && Content.RowKey != null 
      && Content.RowKey.Length > 0 
      && Content.RowKey[0] == 'X'; 
    } 
} 

您可以刪除一些檢查,如果你的構造函數和setter方法驗證這些條件總是假的。例如,如果您在構造函數中設置了內容並向設置器添加了一個檢查來捕獲Content的空分配,則可以刪除Content != null部分。

+0

@TimSchmelter兩者的效率應該相同,因此這是個人偏好的問題。我經常使用'!='我自己,但是我發現'''更常見。 – dasblinkenlight 2012-07-07 13:39:01

0
public Boolean UseRowKey 
{ 
    get 
    { 
     if(!String.IsNullOrEmpty(RowKey)) 
     { 
      return RowKey[0] == 'X'; 
     } 
     return false; 

    } 


} 
0
public bool UseRowkey 
{ 
    get 
    { 
     return this.Content.RowKey[0] == 'X'; 
    } 
} 

順便說一句,看來你做的ViewModel模式錯了。 ViewModel不應該是Model的包裝。 Model的值應該由一些外部代碼映射到ViewModel。例如,使用AutoMapper。

0

還有另一種選擇......這一個接受大寫X和小寫x

public bool UseRowKey 
{ 
    get 
    { 
     return Content != null 
      && !string.IsNullOrEmpty(Content.RowKey) 
      && Content.RowKey 
      .StartsWith("x", StringComparison.InvariantCultureIgnoreCase); 
    } 
}