使用万无一失RequiredIf与枚举 [英] Using Foolproof RequiredIf with an Enum

查看:262
本文介绍了使用万无一失RequiredIf与枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在尝试使用万无一失的验证注解 [RequiredIf] 来检查是否需要一个电子邮件地址。我们还创建了一个枚举避免使用在视图模型查找表ID。代码如下:

We are trying to use the Foolproof validation annotation [RequiredIf] to check if an email address is needed. We also created an enum to avoid using a lookup table id in the ViewModel. The code looks like this:

public enum NotificationMethods {
        Email = 1,
        Fax = 2
}

然后在视图模型:

[RequiredIf("NotificationMethodID", NotificationMethods.Email)]
public string email {get; set;}

在此塞纳里奥我们没有得到一个错误,当电子邮件是空缺,但选作通知类型。相反这种按预期工作:

In this senario we do not get an error when email is unfilled but selected as the notification type. Conversely this works as expected:

[RequiredIf("NotificationMethodID", 1)]
public string email {get; set;}



其他唯一的参考这个,我发现在这里:的 https://foolproof.codeplex.com/workitem/17245

推荐答案

由于你的方法 NotificationMethodID 将返回一个 INT ,原因你检查失败的是,在C#中,每个 枚举 是它自己的类型,从 <$ C继承$ C> System.Enum 。即如果你

Given that your method NotificationMethodID is returning an int, the reason your check is failing is that, in c#, each enum is its own type, inheriting from System.Enum. I.e. if you do

var value = NotificationMethods.Email;
string s = value.GetType().Name;

您将看到取值值为NotificationMethods不是的Int32

如果您尝试直接与枚举检查int的平等,你会得到一个编译器错误:

If you try to check the equality of an int with an enum directly, you get a compiler error:

var same = (1 == NotificationMethods.Email); // Gives the compiler error "Operator '==' cannot be applied to operands of type 'int' and 'NotificationMethods'"

如果您枚举和第一INT值(这是什么情况当它们被传递到 RequiredIfAttribute ),那么就没有编译器错误,但等于()返回false,因为类型不同:

If you box the enum and int values first (which is what happens when they are passed to the constructor of RequiredIfAttribute) then there is no compiler error but Equals() returns false, since the types differ:

var same = ((object)1).Equals((object)NotificationMethods.Email);
Debug.WriteLine(same) // Prints "False".

要检查潜在的整数值,可以显式转换的平等 NotificationMethods.Email 拳击前的一个整数:

To check equality of underlying integer values, you can explicitly cast NotificationMethods.Email to an integer before boxing:

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的值,而不是枚举:

You might also consider using const int values instead of enums:

public static class NotificationMethods
{
    public const int Email = 1;
    public const int Fax = 2;
}

这篇关于使用万无一失RequiredIf与枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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