【问题标题】:pass prop as param to another prop custom attribute c#将 prop 作为参数传递给另一个 prop 自定义属性 c#
【发布时间】:2018-11-29 09:58:19
【问题描述】:

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

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;
    }
}

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

【问题讨论】:

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


【解决方案1】:

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

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

幸运的是,您可以使用一点反射和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

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

【讨论】:

  • 然后,如果您的问题得到解决,请投票(使用向上箭头)并接受它作为正确答案(选择绿色标记)。
猜你喜欢
  • 2020-10-04
  • 2019-03-19
  • 2020-05-03
  • 2020-09-07
  • 1970-01-01
  • 1970-01-01
  • 2023-02-09
  • 1970-01-01
  • 2021-05-11
相关资源
最近更新 更多