【发布时间】:2011-03-29 18:23:25
【问题描述】:
我正在考虑使用扩展方法将 c# 语句链接成如下所示的 jQuery:
foo foo2 =
new foo().Title(foo1.Title)
.Name(foo1.Name)
.DoSomeStuff()
.DoSomeMoreStuff();
这是个好主意还是坏主意?
public class foo
{
public string Title {get;set;}
public string Name {get;set;}
public int Age {get;set;}
public foo(){}
}
public static class fooExtension
{
public static foo Title(this foo source, string title)
{
source.Title = title;
return source;
}
//and other extensions
}
更新:更多解释我正在考虑的“为什么”。 我有两件事:
- 我正在从一个对象获取数据并且 使用它来设置属性 其他。
- 我需要执行一些操作 对这些属性执行操作。
所以我的初始代码看起来更像
foo2.bars = foo1.bars;
foo2.RemoveUnderage();
foo2.NotifyPatronsBarsAreFull();
相反,我认为写起来可能更具描述性:
foo2.bars(foo1.bars).RemoveUnderage().NotifyPatrons();
初始化器很棒,但它们也将所有属性捆绑在一起,我希望属性集接近我将对它们执行的操作。
【问题讨论】:
-
我认为在使用调试器单步执行你想要的方法调用时会有点麻烦。
标签: c# extension-methods method-chaining