将prop作为参数传递给另一个prop自定义属性c#

时间:2018-11-29 09:58:19

标签: c# asp.net-mvc custom-attributes model-validation

我想将一个属性作为参数传递给另一个属性自定义属性,但是我不能,因为它不是静态的 型号ex:

public class model1
{
     public DateTime param1 { get; set; }
     [CustomAttribute (param1)]
     public string param2 { get; set; }
}

public class CustomAttribute : ValidationAttribute
{
    private readonly DateTime _Date;
    public CustomAttribute(DateTime date)
    {
        _Date= date;
    }
}

因为我想在这两个属性之间进行自定义验证。

1 个答案:

答案 0 :(得分:0)

属性不会存储为可执行代码,因此可包含在其中的数据种类受到很大限制。

基本上,您必须坚持基本类型:字符串,数字,日期。一切可能都是常数。

幸运的是,您可以使用一些反射和nameof运算符:

public class model1
{
     public DateTime param1 { get; set; }
     [CustomAttribute (nameof(param1))]
     public string param2 { get; set; }
}

public class CustomAttribute : ValidationAttribute
{
    private readonly string _propertyName;
    public CustomAttribute(string propertyName)
    {
        _propertyName = propertyName;
    }
}

请记住,验证逻辑应位于属性代码之外。

验证所需的要素将是Type.GetPropertiesPropertyInfo.GetValueMemberInfo.GetCustomAttribute

如果您需要一个完整的示例并希望更好地解释用例,请告诉我。