我为一个流畅的有序构造函数创建了一个接口,我写了这段代码:
public interface IMyObjectFactory: IObjectWithProperty
{
int objectId { get; set; }
IObjectWithProperty WithObjectId(int id);
}
public interface IObjectWithProperty
{
IObjectWithProperty WithObjectId(int id);
MyObject Create();
}
第二个接口需要在构造方法
中强制执行顺序impl是这样的:
public class MyObjectFactory: IMyObjectFactory
{
public int objectId { get; set; }
private MyObjectFactory() { }
public static IObjectWithProperty BeginCreation()
{
return new ObjectFactory();
}
public IObjectWithProperty WithObjectId(int id)
{
objectId = id;
return this;
}
public MyObject Create()
{
return new MyObject(this);
}
}
这是我的目标:
public class MyObject
{
public int Id { get; set; }
public MyObject(IMyObjectFactory factory)
{
this.Id = factory.objectId;
}
}
所以我可以写
MyObject mo = MyObjectFactory.BeginCreation().WithObjectId(1).Create();
但:
Warning 7 'FunzIA.DL.Factory.Interfaces.IMyObjectFactory.WithObjectId(int)' hides inherited member 'FunzIA.DL.Factory.Interfaces.IObjectWithProperty.WithObjectId(int)'. Use the new keyword if hiding was intended.
但不是新方法,我需要第二个界面来强制执行命令
有什么建议吗?感谢
答案 0 :(得分:3)
public class MyObjectFactory: IMyObjectFactory
{
private int objectId;
private MyObjectFactory() { }
public static IObjectWithProperty BeginCreation()
{
return new ObjectFactory();
}
public IObjectWithProperty WithObjectId(int id)
{
objectId = id;
return this;
}
public MyObject Create()
{
return new MyObject(objectId);
}
}
public class MyObject
{
public int Id { get; set; }
public MyObject(int objectId)
{
this.Id = objectId;
}
}
我的意见:
WithObjectId
中的IMyObjectFactory
。你通过继承获得它。此设置是您收到警告的原因。BeginCreation
很好。在某些时候,你必须创建真实世界的对象,这是不可能只有接口。你需要真正的课程。MyObject
知道任何工厂。工厂知道并创造物体,而不是相反。 Create
应构建MyObject
。这也导致无需拥有objectId
属性(无论如何你都不喜欢)。答案 1 :(得分:0)
我是这样做的:
public interface IMyObjectFactory: IObjectWithProperty
{
int objectId { get; set; }
}
public interface IObjectWithProperty
{
IObjectWithProperty WithObjectId(int id);
MyObject Create();
}
public class MyObjectFactory: IMyObjectFactory
{
public int objectId;
private MyObjectFactory() { }
public static IObjectWithProperty BeginCreation()
{
return new MyObjectFactory();
}
public IObjectWithProperty WithObjectId(int id)
{
objectId = id;
return this;
}
public MyObject Create()
{
return new MyObject(this);
}
}
public class MyObject
{
public int Id { get; set; }
public MyObject(IMyObjectFactory factory)
{
this.Id = factory.objectId;
}
}