5

我们正在尝试使用 Foolproof 验证注释[RequiredIf]来检查是否需要电子邮件地址。我们还创建了一个枚举以避免在 ViewModel 中使用查找表 id。代码如下所示:

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

然后在 ViewModel 中:

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

在此场景中,当电子邮件未填写但选择为通知类型时,我们不会收到错误消息。相反,这按预期工作:

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

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

4

1 回答 1

5

鉴于您的方法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'"

如果您首先将 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;
}
于 2014-12-14T20:26:56.530 回答