我正在实现一个我想从接口和类继承它的类。当我使用简单的类时它工作得很完美,但我想让它变得通用。当我把它变成通用时它会给出错误。我正在分享我的代码,请指导我。
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public abstract class ValidateCheckBox<TEntity, Validate, IValidate>
where TEntity : class
where Validate :
ValidationAttribute
where IValidate : IClientValidatable
{
public int MinValue { get; set; }
public ValidateCheckBox(int minValue)
{
MinValue = minValue;
ErrorMessage = "At least " + MinValue + " {0} needs to be checked.";
}
public override string FormatErrorMessage(string propName)
{
return string.Format(ErrorMessage, propName);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
try
{
List<CheckboxInfo> valueList = (List<CheckboxInfo>)value;
foreach (var valueItem in valueList)
{
if (valueItem.Selected)
{
return ValidationResult.Success;
}
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
catch (Exception x)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "minchecked",
};
rule.ValidationParameters["minvalue"] = MinValue;
yield return rule;
}
}
答案 0 :(得分:1)
导致错误的问题是您不是从ValidationAttribute继承的。您将其用作约束。见MSDN on constraints。但这带来了其他问题。我不认为支持通用属性。请参阅this和this。
我认为你必须使用它的方式是简单的&#39;:
public abstract class ValidateCheckBox : ValidationAttribute { ... }
通过向自定义属性添加Object
的属性并在使用属性时指定泛型类型,似乎有一种解决方法:
public class GenericClass<T>
{ ... }
public class CustomAttribute : Attribute
{
public System.Object info;
}
然后像这样使用它:
[CustomAttribute(info = typeof(GenericClass<...>))]
...
有关解决方法的更多信息here。