Mat*_*hew 4 c# enums data-annotations foolproof-validation
我们正在尝试使用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.即如果你这样做
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'"
如果框枚举和第一国际价值(也就是当它们被传递到的构造会发生什么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;
}
| 归档时间: | 
 | 
| 查看次数: | 2820 次 | 
| 最近记录: |