首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >更流畅的C# / .NET

更流畅的C# / .NET
EN

Stack Overflow用户
提问于 2009-12-17 01:29:36
回答 18查看 4.8K关注 0票数 15

我的一个同事提出了这个想法,我想知道其他人是怎么想的?就我个人而言,我觉得这很有趣,但我想知道这是不是太偏离了?下面是代码示例。底部的扩展方法。

请给我一个大概的想法。还可以添加其他扩展方法吗?

代码语言:javascript
复制
var ddl = Page.FindControl("LocationDropDownList") as DropDownList;

ddl.Visible = true;
ddl.SelectedValue = "123";

if(isAdmin)
    ddl  .SelectedValue = "111";

变成:

代码语言:javascript
复制
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")));

或者:

代码语言:javascript
复制
 Page.FindControl("LocationDropDownList")
       .CastAs<DropDownList>()
       .With(d =>
       {
           d.Visible = true;
           d.SelectedValue = "123";
       })
       .WithIf(isAdmin, d => d.SelectedValue = "111");

扩展方法:

代码语言:javascript
复制
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;
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1916260

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档