c# – 使用Enum的Foolproof RequiredIf
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 使用Enum的Foolproof RequiredIf,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1708字,纯文字阅读大概需要3分钟。
内容图文
![c# – 使用Enum的Foolproof RequiredIf](/upload/InfoBanner/zyjiaocheng/808/9a7973d464e1478887e7f2ca41befd03.jpg)
我们正在尝试使用Foolproof验证注释[RequiredIf]来检查是否需要电子邮件地址.我们还创建了一个枚举,以避免在ViewModel中使用查找表ID.代码如下所示:
public enum NotificationMethods {
Email = 1,
Fax = 2
}
然后在ViewModel中:
[RequiredIf("NotificationMethodID", NotificationMethods.Email)]
public string email {get; set;}
在此Senario中,当电子邮件未填充但选择作为通知类型时,我们不会收到错误.相反,这可以按预期工作:
[RequiredIf("NotificationMethodID", 1)]
public string email {get; set;}
我发现的唯一其他参考文献是:https://foolproof.codeplex.com/workitem/17245
解决方法:
假设您的方法NotificationMethodID返回一个int,那么检查失败的原因是,在c#中,每个enum都是它自己的类型,继承自System.Enum.I.e.如果你这样做
var value = NotificationMethods.Email;
string s = value.GetType().Name;
你会看到s的值为“NotificationMethods”而不是“Int32”.
如果您尝试直接检查int与enum的相等性,则会出现编译器错误:
var same = (1 == NotificationMethods.Email); // Gives the compiler error "Operator '==' cannot be applied to operands of type 'int' and 'NotificationMethods'"
如果box首先是enum和int值(这是传递给RequiredIfAttribute的构造函数时会发生的情况)那么没有编译器错误但是Equals()返回false,因为类型不同:
var same = ((object)1).Equals((object)NotificationMethods.Email);
Debug.WriteLine(same) // Prints "False".
要检查基础整数值的相等性,您可以在装箱前将NotificationMethods.Email显式转换为整数:
var same = ((object)1).Equals((object)((int)NotificationMethods.Email));
Debug.WriteLine(same); // Prints "True"
并在属性应用程序中:
[RequiredIf("NotificationMethodID", (int)NotificationMethods.Email)]
public string email {get; set;}
您也可以考虑使用const int值而不是枚举:
public static class NotificationMethods
{
public const int Email = 1;
public const int Fax = 2;
}
内容总结
以上是互联网集市为您收集整理的c# – 使用Enum的Foolproof RequiredIf全部内容,希望文章能够帮你解决c# – 使用Enum的Foolproof RequiredIf所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。