2011-09-27 29 views
2

中扩展ModelStateDictionary类,只有AddModelError和Add函数,我想扩展类,添加像AddModeSuccess,AddModelWarning这样的方法。 我看看MVC3源代码,发现有很多东西需要添加。我不想修改MVC3代码,我只是想添加一个扩展。我怎么办?我可以在ModelStateDictionary类的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); 
    } 

回答

1

你可以为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) 
    { 
     ... 
    } 
} 
+1

所以ModelState中还需要添加一些属性或的Fileds? – user928359

相关问题