如何在c#接口中使用泛型类型参数
我有如何在c#接口中使用泛型类型参数,c#,generics,interface,parameters,C#,Generics,Interface,Parameters,我有 公共接口IPersistedModel 我想定义一个接口,其中有一个泛型方法,该方法使用上述泛型类型参数。有办法做到这一点吗?我尝试了以下内容,但都没有编译 public interface IPersistedModel<TModel, TIdentifier> 公共接口IModelCollection1 { IEnumerable ReadCollection(TIdentifier标识符); } 或 公共接口IModelCollection2,其中T:IPersis
公共接口IPersistedModel
我想定义一个接口,其中有一个泛型方法,该方法使用上述泛型类型参数。有办法做到这一点吗?我尝试了以下内容,但都没有编译
public interface IPersistedModel<TModel, TIdentifier>
公共接口IModelCollection1
{
IEnumerable ReadCollection(TIdentifier标识符);
}
或
公共接口IModelCollection2,其中T:IPersistedModel
{
IEnumerable ReadCollection(TIdentifier标识符);
}
您可以简单地使用泛型方法,该方法只向该方法添加泛型参数
public interface IModelCollection2<T> where T : IPersistedModel<TModel, TIdentifier>
{
IEnumerable<TModel> ReadCollection(TIdentifier identifier);
}
A类
{
静态无效交换(左参考、右参考)
{
温度;
温度=lhs;
lhs=rhs;
rhs=温度;
}
}
不幸的是,您需要在接口本身中包含泛型类型:
class A
{
static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
}
公共接口IModelCollection
其中T:IPersistedModel
{
IEnumerable ReadCollection(TIdentifier标识符);
}
试试这个:
public interface IModelCollection<T, TModel, TIdentifier>
where T : IPersistedModel<TModel, TIdentifier>
{
IEnumerable<TModel> ReadCollection(TIdentifier identifier);
}
公共接口Ione,其中T:IIinterfaceOne,其中U:IIinterfacetwo
{
}
公共接口I接口1
{
}
公共接口I接口2
{
}
public interface IModelCollection<T, TModel, TIdentifier>
where T : IPersistedModel<TModel, TIdentifier>
{
IEnumerable<TModel> ReadCollection(TIdentifier identifier);
}
public interface Ione <T, U> where T : IInterfaceOne<T> where U : IInterfaceTwo<U>
{
}
public interface IInterfaceOne<T>
{
}
public interface IInterfaceTwo<U>
{
}