Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 返回可能的通用实现列表_C#_.net_Generics - Fatal编程技术网

C# 返回可能的通用实现列表

C# 返回可能的通用实现列表,c#,.net,generics,C#,.net,Generics,我有以下界面: public interface Query<TModel> { IList<TModel> GetData(); } 使用泛型可以实现这一点吗?您不能使用打开的泛型类型查询,除了内部typeof()。如果要引用一组查询(未指定类型),则需要非通用API,例如: public interface IQuery { IList GetData(); Type QueryType { get; } } public interfa

我有以下界面:

public interface Query<TModel>
{
    IList<TModel> GetData();
}

使用泛型可以实现这一点吗?

您不能使用打开的泛型类型
查询
,除了内部
typeof()
。如果要引用一组查询(未指定类型),则需要非通用API,例如:

public interface IQuery {
     IList GetData();
     Type QueryType { get; }
}
public interface IQuery<TModel> : IQuery
{
    new IList<TModel> GetData();
}    
public interface IQueryProvider
{
   List<IQuery> GetAllQueries();
}
公共接口iquiry{
IList GetData();
类型QueryType{get;}
}
公共接口iquiry:iquiry
{
新的IList GetData();
}    
公共接口提供程序
{
列出GetAllQueries();
}

然而,这意味着您需要为每一个提供
IQuery
的影子实现,这是一个难题。请注意,如果任何服务同时实现了
IQuery
IQuery
,则上述内容也存在歧义,因为没有明显的方式表明
QueryType

您的IQueryProvider必须知道IQuery使用的泛型类型。我能想到两种解决方案

解决方案1:在创建IQueryProvider实例时定义泛型类型

public interface IQueryProvider<TModel>
{
    List<IQuery<TModel>> GetAllQueries();
}
公共接口提供程序
{
列出GetAllQueries();
}
解决方案2:在方法中传入类型

public interface IQueryProvider
{
    List<IQuery<TModel>> GetAllQueries<TModel>();
}
公共接口提供程序
{
列出GetAllQueries();
}

另外,我建议您将查询更改为IQuery,以获得标准命名约定。

如果您扔掉
IList
,并将其替换为
IEnumerable
,您可以使接口协变。不幸的是,这里没有
ReadOnlyList
ReadOnlyCollection
接口(不知道MS在想什么)

公共接口查询
{
IEnumerable GetData();
}
公共接口提供程序
{
列出GetAllQueries();
}

请注意,这仅适用于参考类型
TModel
s.

您希望结果的
类型是什么取决于每个查询实现
public interface IQueryProvider<TModel>
{
    List<IQuery<TModel>> GetAllQueries();
}
public interface IQueryProvider
{
    List<IQuery<TModel>> GetAllQueries<TModel>();
}
public interface Query<out TModel>
{
    IEnumerable<TModel> GetData();
}

public interface IQueryProvider
{
   List<Query<object>> GetAllQueries();
}