Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取/设置为不同的类型_C#_.net_Properties - Fatal编程技术网

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

C# 获取/设置为不同的类型,c#,.net,properties,C#,.net,Properties,我想定义一个变量,该变量将接受集合中的字符串,然后将其转换为Int32,并在GET期间使用它 以下是我目前拥有的代码: private Int32 _currentPage; public String currentPage { get { return _currentPage; } set { _currentPage = (string.IsNullOrEmpty(value)) ? 1 : Convert.ToInt32(value); } }

我想定义一个变量,该变量将接受集合中的字符串,然后将其转换为Int32,并在GET期间使用它

以下是我目前拥有的代码:

private Int32 _currentPage;

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

你所拥有的是它所需要的方式。没有像您所寻求的那样的自动转换。

请注意,将属性get&set用于不同的类型是一个非常糟糕的主意。可能有两种方法更有意义,传递任何其他类型都会破坏此属性

public object PropName
{
    get{ return field; }
    set{ field = int.Parse(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;
}

这避免了格式异常。

使用神奇的get和set块,您别无选择,只能使用返回的相同类型。在我看来,更好的处理方法是让调用代码进行转换,并将类型设置为Int。

好吧,我认为他可能希望处理集合中的无效(而不是null)数据,但他也可能有很好的理由不这样做。一个字符串属性返回int。为什么你会有一个谨慎的方法来设置一个与被设置属性类型相同的参数?他问题中的例子更有意义。在setter中使用代码没有什么错。如果您的方法采用了不同类型的参数(比如int),那么将其与setter分离是有意义的。@Tangled2-这非常有意义。唯一的其他选项是使用无论如何都需要约束的对象。此选项允许完整的编译时类型安全。@John Gietzen:那么您的示例中的CurrentPage属性可能是Int,而不是字符串。@John Gietzen:我看到了您的忍者编辑。;)现在已经修好了,忽略我之前的评论。