鉴于您的方法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;
}