C# c中用于dataannotation的嵌入式资源中的名称常量#
当我创建一个嵌入式资源文件(如C# c中用于dataannotation的嵌入式资源中的名称常量#,c#,c#-4.0,data-annotations,embedded-resource,C#,C# 4.0,Data Annotations,Embedded Resource,当我创建一个嵌入式资源文件(如MyResources.resx)时,我可以使用生成的属性MyResources.MyLabel1从代码(或asp.net视图等)轻松访问这些值。如果我想将其用作数据注释,我会这样写: [Display(Name = "MyLabel1", ResourceType = typeof(MyResources))] public string SomeInput { get; set; } public const string MyLabel1 = "MyLabe
MyResources.resx
)时,我可以使用生成的属性MyResources.MyLabel1
从代码(或asp.net视图等)轻松访问这些值。如果我想将其用作数据注释,我会这样写:
[Display(Name = "MyLabel1", ResourceType = typeof(MyResources))]
public string SomeInput { get; set; }
public const string MyLabel1 = "MyLabel1";
[Display(Name = MyConstants.MyLabel1, ResourceType = typeof(MyResources))]
public string SomeInput { get; set; }
显然,“MyLabel1”现在是一个硬编码字符串,在修改资源、更改或删除名称等时可能会导致问题
我见过人们使用这样的常量:
[Display(Name = "MyLabel1", ResourceType = typeof(MyResources))]
public string SomeInput { get; set; }
public const string MyLabel1 = "MyLabel1";
[Display(Name = MyConstants.MyLabel1, ResourceType = typeof(MyResources))]
public string SomeInput { get; set; }
并将数据注释更改为如下内容:
[Display(Name = "MyLabel1", ResourceType = typeof(MyResources))]
public string SomeInput { get; set; }
public const string MyLabel1 = "MyLabel1";
[Display(Name = MyConstants.MyLabel1, ResourceType = typeof(MyResources))]
public string SomeInput { get; set; }
不过,您仍然需要维护这个硬编码字符串
所以我的问题是:我能以某种方式生成这些名称常量吗?使用自定义T4模板、自定义资源管理器或任何现有工具?因此,更改或删除标签会导致编译错误…有人问过类似的问题。下面是一个生成常量的T4脚本。