我已经构建了一个通用(抽象)构建器,它将为将在测试期间使用的实体构建器提供基本实现。
这是实体基类:
public abstract class Entity : IObjectState
{
[NotMapped]
public ObjectState ObjectState { get; set; }
}
这是IKey 接口:
public interface IKey
{
int Id { get; set; }
}
这是Builder 类:
public abstract class Builder<T> where T : Entity, IKey, new()
{
protected int _id { get; set; }
protected ObjectState _objectState { get; set; }
public Builder()
{
_objectState = ObjectState.Added;
}
public virtual Builder<T> WithId(int id)
{
this._id = id;
return this;
}
public virtual Builder<T> HavingObjectState(ObjectState objectState)
{
_objectState = objectState;
return this;
}
public static implicit operator T(Builder<T> builder)
{
return new T
{
Id = builder._id,
ObjectState = builder._objectState
};
}
}
这是一个示例UnitBuilder实现:
public class UnitBuilder : Builder<Unit>
{
private string _shortDescription;
private string _longDescription;
public UnitBuilder WithShort(string shortDescription)
{
_shortDescription = shortDescription;
return this;
}
public UnitBuilder WithLong(string longDescription)
{
_longDescription = longDescription;
return this;
}
public static implicit operator Unit(UnitBuilder builder)
{
return new Unit
{
Id = builder._id,
ObjectState = builder._objectState,
Short = builder._shortDescription,
Long = builder._longDescription
};
}
}
这就是我遇到的问题:
错误:
错误 CS1061“Builder”不包含“WithShort”的定义,并且找不到接受“Builder”类型的第一个参数的扩展方法“WithShort”(您是否缺少 using 指令或程序集引用?)
我了解发生了什么,但我想要一个比thirdUnit
.
更新:
根据建议,我在UnitBuilder
课堂上添加了以下内容:
public new UnitBuilder WithId(int id)
{
return (UnitBuilder)base.WithId(id);
}
public new UnitBuilder WithObjectState(ObjectState objectState)
{
return (UnitBuilder)base.WithObjectState(objectState);
}
但是现在我在基类中看不到任何意义......这必须是一个通用的通用基类问题,其他人如何处理这个问题?也许thirdUnit
解决方案很优雅,但我只是对此感到困难?:)