2008-08-20 81 views

回答

2

我真的不喜欢串在我的代码,因为它是不可能的重构。一个不错的方法是使用Linq表达式。如果获得通过一个模型作为ViewData的,你可以使用下面的语句:

<%= ShowDropDownBox(viewData => viewData.Name); %> 
... 

public static string ShowDropDownList<T>(this HtmlHelper html, Expression<Action<T>> property) 
{ 
    var body = action.Body as MethodCallExpression; 
    if (body == null) 
     throw new InvalidOperationException("Expression must be a method call."); 
    if (body.Object != action.Parameters[0]) 
     throw new InvalidOperationException("Method call must target lambda argument."); 
    string propertyName = body.Method.Name; 
    string typeName = typeof(T).Name; 

    // now you can call the original method 
    html.Select(propertyName, ...); 
} 

我知道原来的解决方案是执行速度快,但我认为这是一个更清洁。

希望这会有所帮助!

+0

我最后一次尝试refacoring它没有更新我的剃须刀意见 – BlackTigerX 2011-04-09 17:03:30

相关问题