我可以在MVC3中扩展ModelStateDictionary类吗

use*_*359 4 asp.net-mvc-3

在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);
    }
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 6

您可以将它们作为扩展方法添加到ModelStateDictionary类中:

public static class ModelStateExtensions
{
    public static void AddModelSuccess(this ModelStateDictionary modelState, ... some parameters)
    {
        ...
    }

    public static void AddModelWarning(this ModelStateDictionary modelState, ... some parameters)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)