开发者

Get/Set as different types

I'd like to define a variable that will accept a string in the SET, but will then convert it to an Int32 and use that during the GE开发者_开发问答T.

Here the code that I currently have:

private Int32 _currentPage;

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


I would suggest an explicit Set method:

private int _currentPage;

public int CurrentPage
{
    get
    {
        return _currentPage;
    }
}

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

As a side note, your parse method may do better like this:

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

This avoids the formatting exceptions.


Be aware that this is really really bad idea to have a property get & set being used against different types. May be couple of methods would make more sense, and passing any other type would just blow up this property.

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


What you have is the way it needs to be. There are no automatic conversions like you're seeking.


Using the magic get and set blocks, you have no choice but to take the same type you return. In my opinion, the better way to handle it is to have the calling code do the conversions and just make the type an Int.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜