我有几个具有相似方法签名的类,我希望能够在一个接口中进行捕获:
namespace MyLib
public class ClientList
public ICollection<Client> Fetch() {
{
//do stuff
return this.CreateCollection();
}
private ICollection<Client> CreateCollection()
{
List<Client> clientList = new List<Client>();
// populate list
return clientList;
}
public class ProductList
public ICollection<Product> Fetch() {
//do stuff
return this.CreateCollection();
}
private ICollection<Product> CreateCollection()
{
List<Product> productList = new List<Product>();
// populate list
return productList ;
}
我希望您能提供一个方法签名为Fetch并返回ICollection(类型未定义,因为每个列表的类型都不同)的接口。这将确保每个列表对象都有一个fetch方法,并且新的对象将不会有“getList”或其他类似的命名调用。经过一些研究,我认为泛型可能是解决问题的方法,但我不确定如何操作。
我尝试了。
public interface IDataRequest
ICollection<T> Fetch<T>();
但是当我将其实施为
public ICollection<Client> Fetch<Client>()
我在'return this.CreateCollection();'上遇到了一个错误:
无法将类型'System.Collections.Generic.ICollection<MyLib.Client>'隐式转换为类型 'System.Collections.Generic.ICollection<Client>'。已存在显式转换(是否缺少强制转换?)
我想可能是因为没有指定命名空间导致的。但是如果我更改为
public ICollection<MyLib.Client> Fetch<MyLib.Client>()
然后我遇到了以下错误:
类型参数声明必须是标识符而不是类型
出现在 Fetch<MyLib.Client>() 上。
最后,如果我将其更改为:
public ICollection<MyLib.Client> Fetch<Client>()
然后我收到了以下错误信息:
'MyLib.ClientList'未实现接口成员'MyLib.IDataRequest.Fetch()'。 'MyLib.ClientList.Fetch()'无法实现'MyLib.IDataRequest.Fetch()',因为它没有匹配的返回类型'System.Collections.Generic.ICollection'。
我对泛型并不是很了解,并且已经尝试过所有可能的方法,但都无济于事。我想做的事情是否可能?如果可以,请给我展示接口方法签名和类方法定义的示例。
如在评论中请求的那样,这是客户端类:
namespace MyLib
{
using System.Data;
using System.Runtime.Serialization;
[DataContract]
public class Client
{
public Client(DataRow clientRecord)
{
this.clientId = clientRecord.Field<string>("ID");
this.cphh = clientRecord.Field<string>("ID");
this.name = clientRecord.Field<string>("Name");
this.address = clientRecord.Field<string>("Address");
if (CommonUtilities.GIS.ValidateOSMapRef(clientRecord.Field<string>("Locationd")))
{
this.location = string.Format(
"{0}, {1}",
CommonUtilities.GIS.ConvertMapRefToEasting(clientRecord.Field<string>("Locationd")),
CommonUtilities.GIS.ConvertMapRefToNorthing(clientRecord.Field<string>("Locationd")));
}
}
[DataMember]
public string clientId { get; private set; }
[DataMember]
public string name { get; private set; }
[DataMember]
public string address { get; private set; }
[DataMember]
public string location { get; private set; }
[DataMember]
public string cphh { get; private set; }
}
}
using
语句正确。 - Daniel A. WhiteMyLib.Client
是如何声明的?你能发一些它声明的框架代码吗?(包括周围类和/或命名空间的框架) - Lasse V. Karlsen