Gne*_*nex 5 c# interface asp.net-mvc-2
我正在尝试在ASP.NET MVC2中为模型类创建一个接口,我想知道我是否可以List<interface>在另一个接口中使用.如果我给出一个代码示例,那会更好.
我有两个接口,一个终端可以有多个托架.所以我编码我的接口如下.
海湾接口:
public interface IBay
{
// Properties
int id {get; set;}
string name {get;set;}
// ... other properties
}
Run Code Online (Sandbox Code Playgroud)
终端接口:
public interface ITerminal
{
// Properties
int id {get;set;}
string name {get;set;}
// ... other properties
List<IBay> bays {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是当我基于这些接口实现我的类时,如何设置托架列表.我是否必须在ITerminal界面之外和具体实现中进行托架列表?
我的目标是能够做到以下几点:
具体实施:
湾类:
class Bay : IBay
{
// Constructor
public Bay()
{
// ... constructor
}
}
Run Code Online (Sandbox Code Playgroud)
终端类:
class Terminal : ITerminal
{
// Constructor
public Terminal()
{
// ... constructor
}
}
Run Code Online (Sandbox Code Playgroud)
然后就可以访问像这样的托架列表
Terminal.Bays
Run Code Online (Sandbox Code Playgroud)
任何帮助/建议将不胜感激.
您可以通过使用具体实例填充它来初始化接口列表.例如,要Terminal使用对象和集合初始值设定项初始化类,可以使用类似于以下内容的代码:
Terminal terminal = new Terminal
{
id = 0,
name = "My terminal",
bays = new List<IBay>
{
new Bay { id = 1, name = "First bay" },
new Bay { id = 2, name = "Second bay" },
new Bay { id = 3, name = "Third bay" },
}
};
Run Code Online (Sandbox Code Playgroud)
关于你的代码的一些要点:
Id或ID代替id; Name而不是name; Bays而不是bays.bays属性的类型更改List<IBay>为IList<IBay>.这将允许消费者为其分配IBay[]数组.这应该工作正常。只需意识到您的Terminal类仍将包含一个List<IBay>,可以根据需要填充Bay实例。(请注意,我建议您IList<IBay>改用它。)
如果希望终端返回具体Bay类型,则需要重新设计终端接口,并将其修改为:
public interface ITerminal<T> where T : IBay
{
// Properties
int Id {get;set;}
string Name {get;set;}
IList<T> Bays {get;}
}
public Terminal : ITerminal<Bay>
{
private List<Bay> bays = new List<Bay>();
IList<Bay> Bays { get { return bays; } }
// ...
public Terminal()
{
bays.Add(new Bay { //...
Run Code Online (Sandbox Code Playgroud)
但是,增加这种复杂性可能没有什么价值。
| 归档时间: |
|
| 查看次数: |
1310 次 |
| 最近记录: |