Mat*_*hew 4 c# enums data-annotations foolproof-validation
我们正在尝试使用Foolproof验证注释[RequiredIf]
来检查是否需要电子邮件地址.我们还创建了一个枚举,以避免在ViewModel中使用查找表ID.代码如下所示:
public enum NotificationMethods {
Email = 1,
Fax = 2
}
Run Code Online (Sandbox Code Playgroud)
然后在ViewModel中:
[RequiredIf("NotificationMethodID", NotificationMethods.Email)]
public string email {get; set;}
Run Code Online (Sandbox Code Playgroud)
在此Senario中,当电子邮件未填充但选择作为通知类型时,我们不会收到错误.相反,这可以按预期工作:
[RequiredIf("NotificationMethodID", 1)]
public string email {get; set;}
Run Code Online (Sandbox Code Playgroud)
我发现的唯一的另一个参考是:https://foolproof.codeplex.com/workitem/17245
鉴于你的方法NotificationMethodID
正在返回一个int
,你的检查失败的原因是,在c#中,每个enum
都是它自己的类型,继承自System.Enum
.即如果你这样做
var value = NotificationMethods.Email;
string s = value.GetType().Name;
Run Code Online (Sandbox Code Playgroud)
你会看到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'"
Run Code Online (Sandbox Code Playgroud)
如果框枚举和第一国际价值(也就是当它们被传递到的构造会发生什么RequiredIfAttribute
)然后就没有编译器错误,但Equals()
返回false,因为类型不同:
var same = ((object)1).Equals((object)NotificationMethods.Email);
Debug.WriteLine(same) // Prints "False".
Run Code Online (Sandbox Code Playgroud)
要检查基础整数值的相等性,您可以NotificationMethods.Email
在装箱前显式转换为整数:
var same = ((object)1).Equals((object)((int)NotificationMethods.Email));
Debug.WriteLine(same); // Prints "True"
Run Code Online (Sandbox Code Playgroud)
并在属性应用程序中:
[RequiredIf("NotificationMethodID", (int)NotificationMethods.Email)]
public string email {get; set;}
Run Code Online (Sandbox Code Playgroud)
您也可以考虑使用const int
值而不是枚举:
public static class NotificationMethods
{
public const int Email = 1;
public const int Fax = 2;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2820 次 |
最近记录: |