2011-03-22 67 views
6

我想定義一個變量,將接受該集的字符串,但然後將其轉換爲Int32,並使用了GET過程。獲取/設置不同類型的

這裏說我現在有代碼:

private Int32 _currentPage; 

public String currentPage 
{ 
    get { return _currentPage; } 
    set 
    { 
     _currentPage = (string.IsNullOrEmpty(value)) ? 1 : Convert.ToInt32(value); 
    } 
} 
+0

什麼是你的問題? – 2011-03-22 19:30:49

回答

10

我會建議一個明確的Set方法:

private int _currentPage; 

public int CurrentPage 
{ 
    get 
    { 
     return _currentPage; 
    } 
} 

public void SetCurrentPage(string value) 
{ 
     _currentPage = (string.IsNullOrEmpty(value)) ? 1 : Convert.ToInt32(value); 
} 

作爲一個側面說明,你的解析方法可以做到這樣的好:

if (!int.TryParse(value, out _currentPage) 
{ 
    _currentPage = 1; 
} 

這就避免了格式例外。

+0

返回一個int的字符串屬性。 – 2011-03-22 19:33:20

+0

爲什麼要設置一個謹慎的方法,它需要一個與被設置的屬性類型相同的參數?他的問題中的例子更有意義。在setter中使用代碼沒有任何問題。 如果你的方法採取不同的類型(比如,INT),那麼它將使意義它是從模子分開的參數。 – 2011-03-22 19:35:01

+0

@Tangled:它不具有相同的類型......一個是'int',一個是'string' ... – 2011-03-22 19:36:27

0

你有什麼是它需要的方式。沒有像您正在尋找的自動轉換。

+0

那麼,我認爲他可能想要處理該集合中的無效數據(除了null),但他也可能有充分的理由不這樣做。 – 2011-03-22 19:31:59

3

請注意,這是真的不好主意有一個屬性得到&設置用於不同類型。可能是兩個方法會更有意義,而傳遞任何其他類型只會炸掉這個屬性。

public object PropName 
{ 
    get{ return field; } 
    set{ field = int.Parse(value);    
} 
+1

不好的主意是他的正確的想法:) – 2011-03-22 19:33:01

0

使用魔法get和set塊,你別無選擇,只能採取你返還相同種類。在我看來,更好的處理方法是讓調用代碼完成轉換,並將類型設置爲Int。

+0

請問爲什麼你把它們形容爲魔法? – ChaosPandion 2011-03-22 19:44:31