简体   繁体   English

动态注释/属性值

[英]Dynamic annotation/attribute values

I run into a problem using data annotations in c#.我在 c# 中使用数据注释时遇到问题。 I am using custom required and range attributes and I want to set an object as the error message.我正在使用自定义的 required 和 range 属性,并且我想将一个对象设置为错误消息。

[MyOwnRequired(ErrorCode=GlobalMessages.Message01]
public string Description { get; set; }

The problem is that I do have a class holding several objects (GlobalMessages.Message01, each containing a message and a code) in order to translate different error messages throughout the application.问题是我确实有一个类包含多个对象(GlobalMessages.Message01,每个对象包含一条消息和一个代码),以便在整个应用程序中转换不同的错误消息。

As several articles states it is not possible to use a non constant expression as data annotations/attributes.正如几篇文章所述,不可能使用非常量表达式作为数据注释/属性。 I can not use enums to solve this problem since I need to extend the error messages in different projects which is not allowed with enums (inheritance).我不能使用枚举来解决这个问题,因为我需要在不同的项目中扩展枚举(继承)不允许的错误消息。 I also do not want to use the ErrorCode as a String since I want to see the message on each attribute (hover).我也不想将 ErrorCode 用作字符串,因为我想查看每个属性上的消息(悬停)。

Does anyone have a good solution for this problem?有没有人对这个问题有很好的解决方案?

All true.都是真的。 You can not.你不能。 Despite you wrote you can not use enums, this actually can serve a solution:尽管你写了你不能使用枚举,但这实际上可以提供一个解决方案:

Pass enum parameter to your attribute and use this parameter in the attribute constructor's logic/algorithm to implement your extended logic.将枚举参数传递给您的属性,在属性构造函数的逻辑/算法中使用此参数来实现您的扩展逻辑。

Note: This is exactly opposite of some DPs so we safely can call it antipattern, but there is no other choice here.注意:这与某些 DP 完全相反,因此我们可以安全地将其称为反模式,但这里没有其他选择。

If this is an important and verbose part of your project(s) then using an antipattern here could be a productivity killer.如果这是您项目中重要且冗长的部分,那么在这里使用反模式可能会成为生产力杀手。 This case you can also use code generation to generate a partial part of your attribute, and generate the gigantic switch (and its logic) in the constructor automatically, based on some changes in the project.在这种情况下,您还可以使用代码生成来生成属性的一部分,并根据项目中的一些更改在构造函数中自动生成巨大的开关(及其逻辑)。 This eliminates most of the practical drawbacks of the antipattern.这消除了反模式的大部分实际缺点。 (well, it still remains ugly) Recommended tooling this case is T4 which has wide support. (好吧,它仍然很难看)这种情况下推荐的工具是 T4,它具有广泛的支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM