我想構建一個FloatValidatorAttribute。 在這個MSDN文章:https://msdn.microsoft.com/en-us/library/system.configuration.configurationvalidatorattribute(v=vs.110).aspxConfigurationValidatorBase驗證方法接收默認值
有一些例子。 「ProgrammableValidator」及其屬性示例是我想要的浮動驗證器。
我可以找到這個網站的唯一實質性的事情就是這個沒有答案的問題: Validation of double using System.Configuration validator
我也發現了這一點:https://social.msdn.microsoft.com/Forums/vstudio/en-US/6faf9c70-162c-499b-8d0c-0b1f19c7a24a/issues-with-custom-configuration-validator-and-attribute?forum=clr 那人有什麼聽起來像一個類似的問題,因爲我做的。但它對我沒有幫助
我的問題是來自web.config的值未正確傳遞給我創建的FloatValidator的Validate方法。
這是我的代碼:
class FloatValidator : ConfigurationValidatorBase
{
public float MinValue { get; private set; }
public float MaxValue { get; private set; }
public FloatValidator(float minValue, float maxValue)
{
MinValue = minValue;
MaxValue = maxValue;
}
public override bool CanValidate(Type type)
{
return type == typeof(float);
}
public override void Validate(object obj)
{
float value;
try
{
value = float.Parse(obj.ToString());
}
catch (Exception)
{
throw new ArgumentException();
}
if (value < MinValue)
{
throw new ConfigurationErrorsException($"Value too low, minimum value allowed: {MinValue}");
}
if (value > MaxValue)
{
throw new ConfigurationErrorsException($"Value too high, maximum value allowed: {MaxValue}");
}
}
}
屬性它自:
class FloatValidatorAttribute : ConfigurationValidatorAttribute
{
public float MinValue { get; set; }
public float MaxValue { get; set; }
public FloatValidatorAttribute(float minValue, float maxValue)
{
MinValue = minValue;
MaxValue = maxValue;
}
public override ConfigurationValidatorBase ValidatorInstance => new FloatValidator(MinValue, MaxValue);
}
配置元素它自:
public class Compound : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
public string Name => this["name"] as string;
[ConfigurationProperty("abbreviation", IsRequired = true)]
public string Abbreviation => this["abbreviation"] as string;
[ConfigurationProperty("id", IsRequired = true)]
[IntegerValidator(ExcludeRange = false, MinValue = 0, MaxValue = int.MaxValue)]
public int Id => (int)this["id"];
[ConfigurationProperty("factor", IsRequired = true)]
[FloatValidator(float.Epsilon, float.MaxValue)]
public float Factor => (float) this["factor"];
}
下面是從web化合物元素的示例.config
<add name="Ozone" abbreviation="O3" id="147" factor="1.9957"/>
<add name="Particles smaller than 10 µm, Tapered Element Oscillating Microbalance measurement" abbreviation="PM10Teom" id="161" factor="1" />
我可以正確檢索這些值,並且可以將該因子應用於我正在處理的測量值。 但是,如果我應用FloatValidator,所有傳遞給類FloatValidator中Validate()的值都是0,所以我實際上無法驗證輸入。
謝謝你提前
謝謝卡斯爾:) –