在 ModelStateDictionary 类中只有 AddModelError 和 Add 函数,我想扩展类,添加像 AddModeSuccess,AddModelWarning 这样的方法。
我查看了 MVC3 源代码,发现需要添加很多东西。我不想修改 MVC3 代码,我只想添加一个扩展名。我怎么办?
public void Add(KeyValuePair<string, ModelState> item) {
((IDictionary<string, ModelState>)_innerDictionary).Add(item);
}
public void Add(string key, ModelState value) {
_innerDictionary.Add(key, value);
}
public void AddModelError(string key, Exception exception) {
GetModelStateForKey(key).Errors.Add(exception);
}
public void AddModelError(string key, string errorMessage) {
GetModelStateForKey(key).Errors.Add(errorMessage);
}
最佳答案
您可以将它们添加为 extension methods到 ModelStateDictionary
类(class):
public static class ModelStateExtensions
{
public static void AddModelSuccess(this ModelStateDictionary modelState, ... some parameters)
{
...
}
public static void AddModelWarning(this ModelStateDictionary modelState, ... some parameters)
{
...
}
}
关于asp.net-mvc-3 - 我可以在 MVC3 中扩展 ModelStateDictionary 类吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7566701/