using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Creational.Builder
{
public class Person
{
public string Name;
public string Position;
public class Builder : PersonInfoBuilder<Builder>
{
}
public static Builder New => new Builder();
public override string ToString()
{
return $"{nameof(Name)}: {Name}, {nameof(Position)}: {Position}";
}
}
public abstract class PersonBuilder
{
protected Person person = new Person();
public Person Build()
{
return person;
}
}
// class Foo : Bar<Foo>
public class PersonInfoBuilder<SELF> : PersonBuilder
where SELF : PersonInfoBuilder<SELF>
{
public SELF Called(string name)
{
person.Name = name;
return (SELF)this;
}
}
public class PersonJobBuilder<SELF> : PersonInfoBuilder<PersonJobBuilder<SELF>>
where SELF : PersonJobBuilder<SELF>
{
public SELF WorksAsA(string position)
{
person.Position = position;
return (SELF)this;
}
}
internal class Program
{
public static void Main(string[] args)
{
var me = Person.New
.Called("Harry")
.WorksAsA("Testing")
.Build();
Console.WriteLine(me);
var builder = new Builder();
var person = builder.WorksAsA("d").
Console.WriteLine(person);
}
}
}
来自Designpatterns课程的代码,但是它并不完美。我收到以下错误:
Person.Builder'不包含'WorksAsA'的定义,也找不到扩展方法'WorksAsA'接受类型为'Person.Builder'的第一个参数(您是否缺少using指令或程序集引用?)
Builder'是一个命名空间,但其使用方式类似于Creational.Builder
在声明局部变量“ person”之前不能使用
如何解决这些问题?
答案 0 :(得分:0)
公共类Builder:PersonInfoBuilder {
}
必须是:
公共类生成器:PersonJobBuilder {
}
解决了WorksAsa,但没有解决其他问题。