C# 返回C中作为集合的泛型类型#
我已经定义了一个可以以通用方式实现的接口。返回类型必须是一个集合,其中输入参数可以是类或值C# 返回C中作为集合的泛型类型#,c#,.net,generics,C#,.net,Generics,我已经定义了一个可以以通用方式实现的接口。返回类型必须是一个集合,其中输入参数可以是类或值 public interface IDataRetriever<T, C> where T : ICollection<string> { T GetData(C criteria); } 公共接口IDataRetriever,其中T:ICollection { T GetData(C标准); } 当我试图返回一个列表时,我得到一个错误“类型参数T不能用于as操作,因
public interface IDataRetriever<T, C> where T : ICollection<string>
{
T GetData(C criteria);
}
公共接口IDataRetriever,其中T:ICollection
{
T GetData(C标准);
}
当我试图返回一个列表时,我得到一个错误“类型参数T不能用于as操作,因为它没有类类型。”
尝试删除“as T”,但也不起作用
如果我将whereT:ICollection
替换为List
,它会工作。这里有什么不正确的地方
public class CustomADataRetrieverImpl<T, C>: IDataRetriever<T, C>
where T : ICollection<string>
{
public T GetData(C criteria)
{
string myCriteria = criteria as string;
ICollection<string> data = new List<string>()
...
return data as T;
}
}
public类CustomADataRetrieverImpl:IDataRetriever
其中T:i收集
{
公共T GetData(C标准)
{
字符串myCriteria=标准为字符串;
ICollection data=新列表()
...
将数据返回为T;
}
}
希望T是引用(或可为null)类型,这意味着对类的约束也应该包含在签名中
public interface IDataRetriever<T, C>
where T : ICollection<string>, class
{
T GetData(C criteria);
}
公共接口IDataRetriever
其中T:I集合,类
{
T GetData(C标准);
}
正如Jason在注释中提到的,如果T不是字符串类型或从T派生的类型,则将返回null。但是,由于您的约束指定您希望
ICollection
为字符串,这似乎是可以接受的,因为您的问题当前已编写。不是您所问问题的答案,但值得注意的是,您似乎不理解作为
运算符
条件as string
将返回null,除非typeof(C)
已经是string
,使泛型无效
同样,将数据返回为T对于任何不是List
或从List
派生的类型的T
,code>将返回null
。可以考虑使用<代码>新的()/代码>构造函数,允许您直接创建一个新的<代码> t/COD>。
public class CustomADataRetrieverImpl<T, C>: IDataRetriever<T, C>
where T : ICollection<string>, new()
{
public T GetData(C criteria)
{
string myCriteria = criteria.ToString();
T data = new T()
...
return data;
}
}
public类CustomADataRetrieverImpl:IDataRetriever
其中T:ICollection,new()
{
公共T GetData(C标准)
{
字符串myCriteria=criteria.ToString();
T数据=新的T()
...
返回数据;
}
}
如果要将T
和C
修复为列表
和字符串
,则无需将CustomADataRetrieverImpl
设置为通用:
public class CustomADataRetrieverImpl : IDataRetriever<List<string>, string>
{
public List<string> GetData(string criteria)
{
var data = new List<string>();
...
return data;
}
}
public类CustomADataRetrieverImpl:IDataRetriever
{
公共列表GetData(字符串条件)
{
var data=新列表();
...
返回数据;
}
}
应该注意的是,虽然这在技术上是正确的,但可能解决不了任何问题<代码>数据为T
对于任何不是List
或派生类型的T
都将返回null。@JasonWatkins说得很好,虽然在OP的问题中没有特别提出,所以我没有解决它。谢谢,这很有帮助,以前没有看到新的()符号作为参数。看起来很有用。