[英]Error inherit generic class MVC
I'm implementing a class which i want to inherit it from interface and class. 我正在实现一个我想从接口和类继承的类。 It is working perfect when i use simple class but i want to make it generic.
当我使用简单的类但我想使其泛型时,它的工作原理非常完美。 It is giving error when i made it generic.
当我使它通用时,它给出了错误。 I'm sharing my code please guide me.
我正在分享我的代码,请指导我。
[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;
}
}
The issue that is causing the error is that you are not inheriting from ValidationAttribute. 导致该错误的问题是您没有从ValidationAttribute继承。 You're using it as a constraint.
您正在使用它作为约束。 See MSDN on constraints .
有关约束,请参见MSDN 。 But that brings up other problems.
但这带来了其他问题。 I don't think generic attributes are supported.
我认为不支持通用属性。 See this and this .
看到这个和这个 。
I think the way you're going to have to use this is the plain ol': 我认为您必须使用此方法的方式很简单:
public abstract class ValidateCheckBox : ValidationAttribute { ... }
It looks like there is a workaround by adding properties of Object
to your custom attribute and specifying the generic type when using the attribute: 看起来有一种解决方法,即将
Object
的属性添加到自定义属性中,并在使用该属性时指定通用类型:
public class GenericClass<T>
{ ... }
public class CustomAttribute : Attribute
{
public System.Object info;
}
And then using it like this: 然后像这样使用它:
[CustomAttribute(info = typeof(GenericClass<...>))]
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.