条件必选属性,基于c#中的泛型类型



我有一个基类" base "另一类"ran_";它是5个类的父类"RAN1";RAN2",…,"RAN5".

public class RAN {
}
public class RAN1 : RAN {
}
. // RAN2
. // RAN3
. // RAN4
public class RAN5 : RAN {
}
public class BASE<T> where T : RAN {
[Required]
public int Myprop {
get{...}
set{...}    
}
}

我想要这个属性"Myprop"被"要求";当T等于RAN2或RAN4时。这个属性& Myprop"应设置为"非必需"。当T = RAN1, RAN3, RAN5时

我如何做到这一点?

我们可以尝试让Myprop属性为virtual然后我们可以尝试覆盖RAN2RAN4并为其添加Required属性,其他ran只是继承RAN

public class RAN {
public virtual int Myprop { get; set;}
}
public class RAN1 : RAN {
}
public class RAN2 : RAN {
[Required]
public override int Myprop { get; set;}
}
public class RAN4 : RAN {
[Required]
public override int Myprop { get; set;}
}

您必须编写一个自定义的验证属性来实现类似的工作。本页讨论编写自定义属性。还有这个旧的页面,可能有一些相关或有用的信息。

例如,您可以通过继承RequiredAttribute并覆盖受保护的IsValid(object, ValidationContext)方法来编写类似RequiredIfClassHasGenericTypeAttribute的内容。

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Somenamespace
{
public class RequiredIfClassHasGenericTypeAttribute : RequiredAttribute
{
public RequiredIfClassHasGenericTypeAttribute(params Type[] requiredGenericTypes)
{
RequiredGenericTypes = requiredGenericTypes;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var instance = validationContext.ObjectInstance;
var instanceType = instance.GetType();
if (instanceType.GenericTypeArguments.Intersect(RequiredGenericTypes).Any())
{
var result = base.IsValid(value, validationContext);
return result;
}
return ValidationResult.Success;
}
private Type[] RequiredGenericTypes { get; }
}
}

那么你可以这样使用…

public class BASE<T> where T : RAN
{
[RequiredIfClassHasGenericType(typeof(RAN2), typeof(RAN4))]
public int MyProp { get; set; }
}

可能还值得一提的是,RequiredAttribute在注释中指出:

RequiredAttribute属性指定当表单上的字段被验证时,该字段必须包含一个值。如果属性为空、包含空字符串(")或仅包含空白字符,则引发验证异常。

一个int将永远不会是null,包含一个空的string,或只包含空白字符,所以我不确定RequiredAttribute将永远失败的int

最新更新