难道又是一个很好的做法,以存储属性格式的名字在公共字符串常量? [英] Is is a good practice to store propery names in a public constant string?

查看:124
本文介绍了难道又是一个很好的做法,以存储属性格式的名字在公共字符串常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了保护因性质(比方说,你可以回复你的POCO类,因为你已经改变了相关的数据库表的一些字段名)是一个很好的做法,decalre是守财产常量字符串的任何重新命名我们自己从失败里面的名字?

In order to protect ourself from failure because of any renaming of properties (Let's say you regenerate your poco classes because you have changed some column names in the relevant Db table) is it a good practice to decalre constant strings that keep the property names inside?

public const string StudentCountPropertyName = "StudentCount";
public int StudentCount {get;set;}

例如:想想一个数据绑定;在那里你在DataFieldName键入属性的名称明确属性。

For example: Think about a DataBinding; where you type the property name in the DataFieldName attribute explicitly.

或者这是不是一个好主意,有一个更好,还是更安全的方式?

Or this is not a good idea and there is a better and still safer way?

推荐答案

它始终是一个好主意,恕我直言,移动任何神奇字符串常量。

It is always a good idea IMHO to move any 'magic strings' to constants.

您可以考虑使用lambda EX pressions以'挑'的特性,例如:

You could consider using lambda expressions to 'pick' your properties, for example:

GetDataFieldName(studentCollection => studentCollection.Count)

您必须实施 GetDataFieldName 自己,用有点反思。你可以看一下 HtmlHelperExtensions 从MVC,看看它是如何可以做到的。这将是最安全的方法,它给你编译时错误出问题的时候,并可以轻松财产使用现有的重构工具重命名。

You will have to implement GetDataFieldName yourself, using a bit of reflection. You can look at HtmlHelperExtensions from MVC to see how it can be done. This will be the most safe approach, which gives you compile-time errors when something goes wrong and allows easy property renaming using existing refactoring tools.

这篇关于难道又是一个很好的做法,以存储属性格式的名字在公共字符串常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆