在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);
}
答案 0 :(得分:5)
您可以将它们extension methods添加到ModelStateDictionary
类:
public static class ModelStateExtensions
{
public static void AddModelSuccess(this ModelStateDictionary modelState, ... some parameters)
{
...
}
public static void AddModelWarning(this ModelStateDictionary modelState, ... some parameters)
{
...
}
}