如果我非一般的生成器類使用隱式操作每一件事情是確定的:這使用泛型隱式運算符有什麼問題?
public class ReligionBuilder
{
private Religion _religion;
public ReligionBuilder()
{
_religion = new Religion(){//some codes}
}
public ReligionBuilder AddToRepository()
{
Repository<Religion>.Add(_religion);
return this;
}
public Religion Build()
{
return _religion;
}
public static implicit operator Religion(ReligionBuilder _builder)
{
return _builder.Build();
}
}
我可以用它:
Religion religion=new ReligionBuilder().AddToRepository();
但如果運營商是通用類的東西是錯誤的:
public abstract class DataTestBuilderBase<T> : IDataTestBuilder<T>
{
protected T TestData { get; set; }
public virtual T Build()
{
return TestData;
}
public abstract IDataTestBuilder<T> AddToRepository();
public abstract IDataTestBuilder<T> WithDefault();
public static implicit operator T(DataTestBuilderBase<T> builder)
{
return builder.Build();
}
}
public class PersonDataTestBuilder : DataTestBuilderBase<Person>
{
private Person _person;
public PersonDataTestBuilder()
{
//some codes
}
public override IDataTestBuilder<Person> AddToRepository()
{
//some codes
return this;
}
}
用法:
PersonDataTestBuilder _testBuilder = new PersonDataTestBuilder();
Person person = _testBuilder.AddToRepository();
錯誤是:無法將IDataTestBuilder轉換爲Person
有什麼問題?
只是一個側面說明,但我們也開始用我們自己的工具建設者,但我們最終使用http://nbuilder.org/它真的很好,並有很多功能。 – 2012-01-16 08:03:45