我有一个日期格式,如:
[displayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:MM/dd/yyyy}")] public DateTime? CreatedOn { get; set; }
现在,我想让我的应用程序中的每个日期时间格式从一个配置文件中读取.喜欢:
[displayFormat(ApplyFormatInEditMode = true,DataFormatString = SomeClass.GetDateFormat())] public DateTime? CreatedOn { get; set; }
但这不会编译.
我怎样才能做到这一点?
解决方法
这个问题是.NET只允许你将编译时常量放在属性中.另一种选择是继承displayFormatAttribute并在构造函数中查找显示格式,如下所示:
SomeClass.cs
public class SomeClass { public static string GetDateFormat() { // return date format here } }
DynamicdisplayFormatAttribute.cs
public class DynamicdisplayFormatAttribute : displayFormatAttribute { public DynamicdisplayFormatAttribute() { DataFormatString = SomeClass.GetDateFormat(); } }
然后您可以这样使用它:
[DynamicdisplayFormat(ApplyFormatInEditMode = true)] public DateTime? CreatedOn { get; set; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。