尝试实现 DecimalAboveThresholdAttribute 有问题
我正在尝试实现类似于 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 来做到这一点。
I am trying to implement something similar to IntegerAboveThresholdAttribute except that it should work with decimals.
This is my implementation of me using it as a BusinessException
[DecimalAboveThreshold(typeof(BusinessException), 10000m, ErrorMessage = "Dollar Value must be 10000 or lower.")]
However, I receive an error saying An attribute must be a constant expression, typeof expression, or array creation expression of an attribute parameter type. I was wondering if it is possible to fix this, and if not, is it possible to do something similar?
Here is the source code for 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;
}
}
}
I also would like to know if I can do this with DateTimes as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不允许使用小数作为属性参数。这是 .NET 属性中的内置限制。您可以在 MSDN。所以它不适用于十进制和日期时间。作为一种解决方法(尽管它不是类型安全的),您可以使用字符串:
用法:
You are not allowed to use decimals as attribute parameters. This is a built in restriction in .NET attributes. You can find the available parameter types on MSDN. So it won't work with decimal and DateTime. As a workaround (although it won't be typesafe) you can use strings:
Usage: