0

我正在尝试实现类似于 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 来做到这一点。

4

1 回答 1

2

不允许使用小数作为属性参数。这是 .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.")]
于 2011-11-02T20:50:02.570 回答