我的一个同事提出了这个想法,我想知道其他人是怎么想的?就我个人而言,我觉得这很有趣,但我想知道这是不是太偏离了?下面是代码示例。底部的扩展方法。
请给我一个大概的想法。还可以添加其他扩展方法吗?
var ddl = Page.FindControl("LocationDropDownList") as DropDownList;
ddl.Visible = true;
ddl.SelectedValue = "123";
if(isAdmin)
ddl .SelectedValue = "111";
变成:
Page.FindControl("LocationDropDownList")
.CastAs<DropDownList>()
.With(d => d.Visible = true)
.With(d => d.SelectedValue = "123")
.WithIf(isAdmin, d => d.Items.Add(new ListItem("Admin", "1")));
或者:
Page.FindControl("LocationDropDownList")
.CastAs<DropDownList>()
.With(d =>
{
d.Visible = true;
d.SelectedValue = "123";
})
.WithIf(isAdmin, d => d.SelectedValue = "111");
扩展方法:
public static TResult CastAs<TResult>(this object obj) where TResult : class
{
return obj as TResult;
}
public static T With<T>(this T t, Action<T> action)
{
if (action == null)
throw new ArgumentNullException("action");
action(t);
return t;
}
public static T WithIf<T>(this T t, bool condition, Action<T> action)
{
if (action == null)
throw new ArgumentNullException("action");
if (condition)
action(t);
return t;
}
发布于 2009-12-17 01:34:38
除了让读者感到困惑之外,我看不出这样做有什么好处。关于我的同伴回答,我想知道这是在哪个星球上更具可读性。据我所知,第一个版本或多或少具有完美的可读性,而这是相当可读的,但这会让读者怀疑With
和WithIf
中是否发生了一些奇怪的魔术。
与第一个版本相比,它更长,更难输入,不那么明显,性能也更差。
发布于 2009-12-17 01:34:58
我想我看不出新版本给你带来了什么。原文写得很清楚,也没那么冗长。我猜它也会更快。我会避免使用(滥用?)这样的语言特性,除非有明显的好处。
发布于 2009-12-17 01:52:23
再投一票给“没用的”。With
扩展方法除了用一个方法包装已排序的语句之外,什么也不做。C#已经有了一个内置的语句排序函数,它的名字叫;
。
类似地,WithIf
包装了一个if语句,而不对控制流进行任何修改。在我看来,您只会邀请自己使用以下方法:
public static T For<T>(
this T t, int start, Func<int, bool> cond, Action<T, int> f)
{
for(int i = start; cond(i); i++)
{
f(t, i);
}
return t;
}
https://stackoverflow.com/questions/1916260
复制相似问题