我试图将输入数据的验证移入get; set;的类结构。get; set;与DateTime与.TryParse验证?
public void PlotFiles()
{
List<DTVitem.item> dataitems;
DTVitem.item i;
DateTime.TryParse("2012/01/01", out i.dt);
DateTime.TryParse("04:04:04", out i.t);
int.TryParse("455", out i.v);
dataitems.Add(i);
}
的结构也是在一个单独的类(可能是不必要的)声明:
public partial class DTVitem
{
public struct item
{
public DateTime dt;
public DateTime t;
public int v;
}
}
我每次设置DTVitem.item.dt
,DTVitem.item.t
,或DTVitem.item.v
,我希望它来执行相关.TryParse()
要验证的属性内容。
然而,当我尝试使用的TryParse()如下(试图环绕this example from MSDN我的头):
public partial class DTVitem
{
private DateTime _datevalue;
public string dt
{
get { return _datevalue; }
set { DateTime.TryParse(value, out _datevalue) ;}
}
}
我收到错误_datevalue is a DateTime and cannot be converted to a string
。原因很明显,在这种情况下返回路径必须返回dt
的类型(一个string
)。但是,我试图用几种不同的方式来按摩这些东西,并且无法破解它。
将其设置为结构实例的属性时,如何实现验证string
值为DateTime
的目标?
正在使用set
,因为我正试图以最好的方式?
我可以看到使用get; set;有很多的价值;进行验证,并且真的很想了解它。
非常感谢,
马特
[编辑]
感谢以下Jon Skeet您指出我的方式犯错。
Here's another thread on problems with mutable structs,and another speaking about instantiating a struct。注意structs are value types。
我相信他指出的其余部分只是认为将结构化的方式埋在很远的地方是没有必要的,我应该回顾一下为什么要这样做。
[解决方案]
我已经考虑了以下一些建议,并提出了以下几点:
public partial class DTVitem
{
private DateTime _dtvalue, _tvalue;
private int _vvalue;
public string dt
{
get { return _dtvalue.ToString(); }
set { DateTime.TryParse(value, out _dtvalue); }
}
public string t
{
get { return _tvalue.ToString(); }
set { DateTime.TryParse(value, out _tvalue); }
}
public string v
{
get { return _vvalue.ToString(); }
set { int.TryParse(value, out _vvalue); }
}
}
里面我的程序类,我实例化,并具有以下设置:
DTVitem item = new DTVitem();
item.dt = "2012/01/01";
item.t = "04:04:04";
item.v = "455";
所以我选择不使用结构,而是一个类;或者真的是这个类的一个实例。
这很不清楚为什么你在'DTVitem'中有一个公共字段作为嵌套类型的公共可变结构。所有这些对我来说都是一个糟糕的主意。 – 2013-02-19 21:27:42
你的错误是因为你在'get'中返回一个'DateTime'来声明一个被声明为'string'的属性。 – juharr 2013-02-19 21:29:36
Get和Set应该只能获取并设置一个变量。这听起来像一个类对你来说比一个结构更有用,至少是你使用它的方式。片段调用集应负责使用有效的DateTime而不是struct/class。 – 2013-02-19 21:30:53