c# - 获取/设置为不同的类型

标签 c# .net properties

我想定义一个变量,它将接受 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/

相关文章:

c# - 误报 : Fix this implementation of IDisposable to conform to the dispose pattern

c# - 在运行时实例化时动态包装 C# 方法的内容

php - 从类中变量的函数中获取值

python - 在 Python 中定义未更改的公共(public)变量是一个好习惯吗?

c# - 电子邮件删除附件后,错误 "The process cannot access the file because it is being used by another process."

c# - 开发向导 UI - WPF

SSIS 中的 C# 脚本任务

c# - 如何使用 MySqlDataReader 从数据库中检索值?

.net - .net core 6 中长时间运行的函数

javascript - 带赋值的可选链接