2011-11-02 31 views
0

我想實現類似於IntegerAboveThresholdAttribute的東西,除了它應該與小數工作。試圖實現與問題的DecimalAboveThresholdAttribute

這是使用它作爲一個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; 
    } 
} 

}

我也想知道如果我能做到這一點與DateTime是否爲好。

回答

1

您不允許使用小數作爲屬性參數。這是.NET屬性中的內置限制。您可以在MSDN上找到可用的參數類型。所以它不會使用十進制和DateTime。作爲一種變通方法(雖然它不會是類型安全的),您可以使用字符串:

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

用法:

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