【发布时间】:2015-06-01 10:14:35
【问题描述】:
我希望在接口中捕获具有相似方法签名的多个类:
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,类型为 undefined(因为每个列表都不同)。这将确保每个 *list 对象都有一个 fetch 方法,而新对象不会有 'getList' 或其他此类命名调用。在做了一些研究之后,我相信仿制药可能是要走的路,但我不确定如何。
我试过了
public interface IDataRequest
ICollection<T> Fetch<T>();
但是当我把它实现为
public ICollection<Client> Fetch<Client>()
'return this.CreateCollection();'时出现错误:
不能隐式转换类型 'System.Collections.Generic.ICollection
' 到 'System.Collections.Generic.ICollection '。显式 存在转换(您是否缺少演员表?)
我想可能是因为我没有指定命名空间。但如果我改成
public ICollection<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; }
}
}
【问题讨论】:
-
确保您的
usings 是正确的。 -
方法中的 return 语句返回的集合与您声明要返回的方法不同类型的集合。
MyLib.Client是如何声明的?你能发布一些它的声明的骨架代码吗? (包括围绕类和/或命名空间的骨架) -
@DanielA.White 所有这些类都在同一个命名空间中,还有什么我需要注意的。
-
@LasseV.Karlsen Fetch方法返回Client的ICollection,CreateCollection方法返回Client的ICollection(List)。这就是为什么第一次尝试错误消息让我感到困惑的原因。我会将客户添加到原始问题中
-
有一个特殊的语句将模板限制为一个类型:msdn.microsoft.com/en-us/library/d5x73970.aspx,也许它可以帮助你的情况......