gpt4 book ai didi

c# - 更流畅的 C#/.NET

转载 作者:可可西里 更新时间:2023-11-01 03:11:30 27 4
gpt4 key购买 nike

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

一般的想法请。可以添加其他扩展方法吗?

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;
}

最佳答案

我编写清晰代码的经验法则是:将所有副作用放在语句中;非语句表达式应该没有副作用。

您的程序的第一个版本显然遵循了这条规则。第二个版本显然违反了它。

另一个想法:如果我要像您显示的代码一样阅读代码,我自然会假设代码的目的是构建一个代表那些操作的惰性求值结构——这就是为什么C# 3 中的查询理解就是以这种方式构建的。查询表达式的结果是一个对象,表示查询的延迟应用。

如果您的意图是捕捉“在我选择的稍后时刻以延迟方式执行这些副作用”的概念,那么这是一个明智的方法。本质上,你正在构建的是一个有副作用的 monad。如果您的意图仅仅是为急切执行的代码提供不同的语法,那么这只会造成混淆、冗长和不必要。

关于c# - 更流畅的 C#/.NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1916260/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com