【问题标题】:Need a sample function implement for array interface member需要数组接口成员的示例函数实现
【发布时间】:2010-03-09 06:24:46
【问题描述】:
我有一个这样的接口成员。
AppInterface.cs
ObjLocation[] ArrayLocations { get; }
App.cs
public ObjLocation[] ArrayLocations
{
get
{
return **something**;
}
}
我不知道如何完成,或者还有其他方法来实现数组成员。
然后它可以通过编译器。谢谢。
【问题讨论】:
标签:
c#
interface
implementation
【解决方案1】:
好吧,你只需要返回一个数组:
public ObjLocation[] ArrLocations
{
get
{
ObjLocation[] locations = new ObjLocation[10];
// Fill in values here
return locations;
}
}
或者,如果您已经拥有 List<ObjLocation>,您可以这样做:
public ObjLocation[] ArrLocations
{
get
{
return locationList.ToArray();
}
}
当我们不知道属性的用途或您拥有什么数据时,很难知道建议您为属性正文写什么。
您应该仔细考虑非常的一件事是如果调用者更改数组内容会发生什么。如果你的类中有一个数组并且你只是返回一个对它的引用,那么调用者就能够弄乱你的数据——这 可能 不是你想要的。没有办法返回一个“只读”数组,因为没有这样的概念——这就是他们是considered somewhat harmful 的原因之一。 (如果接口指定您必须返回IList<ObjLocation> 或IEnumerable<ObjLocation>,那就更好了。)
如果这还不足以解决您的问题,请提供更多信息。
【解决方案2】:
return new ObjLocation[size] 或 return new ObjLocation[] { objLocationInstance1, objLocationInstance2, ... }