我想定义一个变量,它将接受 SET 中的字符串,然后将其转换为 Int32 并在 GET 期间使用它。
这是我目前拥有的代码:
private Int32 _currentPage;
public String currentPage
{
get { return _currentPage; }
set
{
_currentPage = (string.IsNullOrEmpty(value)) ? 1 : Convert.ToInt32(value);
}
}
最佳答案
我会建议一个明确的 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;
}
这避免了格式异常。
关于c# - 获取/设置为不同的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5396713/