C# 具有子泛型类型的泛型工厂方法
我有一个InterfaceExecuter类型,定义为Enter和Exit类型,两者都是struct。 在另一个类中,我想创建一个方法,该方法实例化实现我的接口的类,如下所示:C# 具有子泛型类型的泛型工厂方法,c#,generics,C#,Generics,我有一个InterfaceExecuter类型,定义为Enter和Exit类型,两者都是struct。 在另一个类中,我想创建一个方法,该方法实例化实现我的接口的类,如下所示: public T<TEntry, TExit> Initiate<T<TEntry, TExit>>() where T: InterfaceExecuter<TEntry, TExit>, new() where TEntry:struc
public T<TEntry, TExit> Initiate<T<TEntry, TExit>>()
where T: InterfaceExecuter<TEntry, TExit>, new()
where TEntry:struct
where TExit:struct
{
return new T<TEntry, TExit>();
}
public T Initiate()
其中T:interfaceeexecuter,new()
其中TEntry:struct
其中TExit:struct
{
返回新的T();
}
我该怎么做呢?您就快到了,只需将返回类型
(T)
定义为泛型参数即可
使用此约束T:InterfaceeExecuter
您已经定义了泛型类型T
的结构,因此在实例化泛型类型时不需要显式使用泛型参数(编译器也不允许)
public T Initiate()
其中T:interfaceeexecuter,new()
其中TEntry:struct
其中TExit:struct
{
返回新的T();
}
当然可以!但是,我需要像这样调用这个方法吗?this.Initiate()在这种情况下,我应该传递结构类型两次,一次用于ConcreteExecutor,另一次用于Initiate方法。是吗?是的,你们需要在这两个地方提供TEntry和TExit。
public T Initiate<T, TEntry, TExit>()
where T: InterfaceExecuter<TEntry, TExit>, new()
where TEntry:struct
where TExit:struct
{
return new T();
}