【发布时间】:2013-07-23 02:51:40
【问题描述】:
为了让我的代码更有条理,我决定使用流畅的接口;但是通过阅读可用的教程,我发现了很多实现这种流畅性的方法,其中我发现了一个主题,说要创建 Fluent Interface 我们应该使用Interfaces,但他没有按顺序提供任何好的细节去实现它。
这是我实现 Fluent API 的方式
代码
public class Person
{
public string Name { get; private set; }
public int Age { get; private set; }
public static Person CreateNew()
{
return new Person();
}
public Person WithName(string name)
{
Name = name;
return this;
}
public Person WithAge(int age)
{
Age = age;
return this;
}
}
使用代码
Person person = Person.CreateNew().WithName("John").WithAge(21);
但是,我怎样才能让接口以更有效的方式创建 Fluent API?
【问题讨论】:
-
这种方式有什么不好的地方?
-
@Sergey 我只是想知道如何使用那些家伙所说的接口来实现这样的 Fluent API...而且我不喜欢使用 With***,而是我想使用 Name、Age、等等......但由于属性名称,我不能在这种情况下
-
有没有提到“那个家伙”?很高兴看到更大的问题,因为在这种情况下,您可以简单地执行 'new Person { Name="John", Age=21 }'
-
我认为在这篇博客中,他为非常简单的问题提供了非常复杂的解决方案,对不起。
标签: c# fluent-interface