具有泛型类型参数的Net泛型类型
本文关键字:Net 泛型类型 泛型类型参数 | 更新日期: 2023-09-27 18:27:10
这在任何其他语法中都可能吗???
interface IFoo<T<U>> where U: Bar, new() where T<U>: class, IFoo<T<U>>, new()
这是一种强制IFoo的泛型参数为泛型类型的方法
class MyFoo<U>: IFoo<MyFoo<U>> where U: Bar, new()
编辑以说明一些要点:
- U是条形。。。它将是一个客户实体
- T是IFoo。。。它将是一个客户业务对象
- IFoo是一些业务对象的接口
- IFoo定义
List<U> GetList(int compareToCustomerProperty)
编辑以说明可用性:
interface IFoo<T<U>> where U: Bar, new() where T<U>: class, IFoo<T<U>>, new()
T<U> DoOnce();
class MyFoo<U>: IFoo<MyFoo<U>> where U: Bar, new()
MyFoo<U> DoOnce(){return this;}
MyFoo<U> DoAgain(){return this;}//this is not in interface
class Test{
public Test(){
IFoo<MyFoo<Bar>> x = new MyFoo<Bar>();//Generics can come as parameters
x.
DoOnce()//this is from interface
DoAgain();//Can access this x's method cause of generic in IFoo
}
}
我目前可以实现它,但我失去了通用的U.
没有它可以生活吗???总计
我会在代码中的某个时刻错过这种方法吗???不!
我刚刚到了一个地步,我看到在我的代码中有这一点会很好(抽象和具体之间的方法链接,泛型中更自由)
谢谢你的回答!
唯一接近我认为您正在尝试做的事情是
public interface IBaz<U>
{
}
public class Baz<U> : IBaz<U>
{
}
public interface IFoo<T, U> where T : IBaz<U> where U: Bar, new()
{
}
public class Foo<U> : IFoo<Baz<U>, U>
where U: Bar, new()
{
}
不,在.Net框架中不能做到这一点。
请看,将泛型类型参数限制为泛型本身并没有多大意义。考虑以下类型:
public class StringList : List<string> { }
CCD_ 2和CCD_。但是你可以写
Foo<List<string>>
而不是
Foo<StringList>
List<string>
是从泛型类型定义List<>
创建的,这一事实与大多数用法并不相关,除非您正在处理某种面向反射的高级行为。
例如,我可以看到,如果你想做这样的事情,你可能想要这种功能:
public interface GenericTypeConverter<T> where T : <>
{
T<V> Convert<U,V>(T<U> thing);
}
如果您想创建一个Converter接口,该接口声明要从T<U>
转换为T<V>
的函数,则适用于任意泛型类型T
。但我只能想象,如果你从事复杂的代码生成/代码分析,就会发生这种情况。
如果是这种情况并且您确实需要,您可以在运行时通过调用typeof(T).IsGenericType
T
是否为泛型