【问题标题】:Trying to Implement DecimalAboveThresholdAttribute with problems尝试实现有问题的 DecimalAboveThresholdAttribute
【发布时间】:2011-11-02 20:33:32
【问题描述】:

我正在尝试实现类似于 IntegerAboveThresholdAttribute 的东西,除了它应该使用小数。

这是我将其用作 BusinessException 的实现

[DecimalAboveThreshold(typeof(BusinessException), 10000m, ErrorMessage = "Dollar Value must be 10000 or lower.")]

但是,我收到一条错误消息,指出属性必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式。我想知道是否有可能解决这个问题,如果没有,是否可以做类似的事情?

这里是 DecimalAboveThresholdAttribute 的源代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoreLib.Messaging;

namespace (*removed*)
{
public class DecimalBelowThresholdAttribute : BusinessValidationAttribute
{
    private decimal _Threshold;

    public DecimalBelowThresholdAttribute(Type exceptionToThrow, decimal threshold)
        : base(exceptionToThrow)
    {
        _Threshold = threshold;
    }

    protected override bool Validates(decimal value)
    {
        return (decimal)value < _Threshold;
    }
}

}

我也想知道我是否也可以使用 DateTimes 来做到这一点。

【问题讨论】:

    标签: c# asp.net validation exception business-rules


    【解决方案1】:

    您不能使用小数作为属性参数。这是 .NET 属性中的内置限制。您可以在MSDN 上找到可用的参数类型。所以它不适用于十进制和日期时间。作为一种解决方法(尽管它不是类型安全的),您可以使用字符串:

    public DecimalBelowThresholdAttribute(Type exceptionToThrow, string threshold)
            : base(exceptionToThrow)
        {
            _Threshold = decimal.Parse(threshold);
        }
    

    用法:

    [DecimalAboveThreshold(typeof(BusinessException), "10000", ErrorMessage = "Dollar Value must be 10000 or lower.")]
    

    【讨论】:

      猜你喜欢
      • 2013-01-11
      • 2011-10-31
      • 1970-01-01
      • 2018-04-29
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 2016-04-07
      相关资源
      最近更新 更多