猿问

如何使用 Dictionary<int, object> 上的 Required 属性来防止空值?

我有一个类,其中包含一个Dictionary<int, object>标记为必需的属性。当我将进入控制器的数据反序列化到该类上时,该Required属性会阻止nulls 进入该属性,但它不会阻止nulls 作为值输入字典,因为键值对已正确格式化和传递。


有没有办法让Required属性也阻止nulls 成为字典中的值?或者是否可以向该属性添加另一个属性来完成此操作?


或者解决这个问题的最好方法是推出我自己的类,该类基本上由键值对组成,我可以将键属性和值属性标记为Required?前任:


public class Example

{

    [Required]

    public int Key;


    [Required]

    public object Value;

}

然后只是有一个IEnumerable<Example>而不是Dictionary<int, object>?


慕尼黑的夜晚无繁华
浏览 118回答 2
2回答

海绵宝宝撒

我能想到的最好的方法是ISet<Example>(使用 a&nbsp;HashSet<Example>)覆盖Example'sGetHashCode和方法。Equals那应该满足你的第二个愿望。至于[Required]属性,您必须自己编写代码以检查这些属性是否不为空,然后再将其添加到ISet<Example>.&nbsp;这可能需要一些反射逻辑。

心有法竹

这就是我最终的结果,它完全按照我想要Required的方式工作。[AttributeUsage(AttributeTargets.Property)]public class DictionaryRequiredAttribute : ValidationAttribute{&nbsp; &nbsp; public DictionaryRequiredAttribute() : base(() => "The {0} field is required and cannot contain null values.") { }&nbsp; &nbsp; public override bool IsValid(object value)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (value == null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (value is IDictionary dictValue)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach (var key in dictValue.Keys)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (dictValue[key] == null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }}主要是根据这里RequiredAttribute找到的执行。
随时随地看视频慕课网APP
我要回答