初始化 DataTable 中的某些值时我们应该使用什么
当您想从数据表初始化类属性时,应该使用什么更合适。
即
name=dt.Rows[0][0] or name=dt.Rows[0]["Name"]
哪种方法更具可扩展性且易于处理。 目前我使用第二种方法,但感觉如果我使用索引而不是名称,我只需要更改存储过程而不是 UI。
但会损害代码的可读性。那么我应该做什么
What should be more appropriate to use when you want to initialize class properties from datatable.
i.e.
name=dt.Rows[0][0] or name=dt.Rows[0]["Name"]
Which approach is more scalable any easy to handle.
Currently I uses 2nd approach but feels like if I use indexes rather than name that i only need to change stored procedures rather that UI also.
But compromises readability of code. So What should I go for
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种选择是介于两者之间:
如果列排序/定义发生更改,这将为您提供一个进行更改的位置,而且还可以在访问点提供可读的代码。我不确定它是否解决了必须同时更改 UI 代码和存储过程的问题:如果您的 SP 有效地更改了其公共界面,那么您应该期望更改 UI代码。然而,这种方法可以减少更改带来的痛苦,并且不会在代码中乱扔神奇的值。
(您可能还想考虑强类型数据集...或迁移到非
DataTable
数据解决方案,例如实体框架。它可能不适合您的情况,但值得考虑。)One option is to have something in between:
That gives you one place to change if the column ordering/definitions change, but also gives readable code at the point of access. I'm not sure it addresses the issue of having to change both the UI code and the stored procedures at the same time: if your SPs are effectively changing their public interface, you should expect to change the UI code. However, this approach can reduce the pain of that change, as well as not littering your code with magic values.
(You might also want to consider strongly typed datasets... or moving to a non-
DataTable
data solution such as the Entity Framework. It may not be appropriate in your situation, but it's worth considering.)列名称,因为它使其更具可读性。如果您要更改存储过程,那么使用列索引不会有太大帮助,因为您可能会更改列的数量或顺序。
Column names, as it makes it all more readable. If you're going to change stored procedures, using column indexes won't help much cause you might be changing the number or the order of columns.
使用数字索引比重复使用字符串索引更快。您可以在循环遍历表行之前在运行时计算一次数字索引,如下所示:
Using a numeric index is faster than repeatedly using the string index. You can compute the numeric index at runtime once before you loop through table rows like so: