2012-03-07 191 views
0

这是否可以用任何其他语法?带泛型类型参数的网络泛型类型

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 is IFoo ...它将成为客户业务对象
  • IFoo is interfa行政长官对一些业务对象
  • 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.

可以没有它? ?共
我会错过这种方法在我的代码中的某个点?罗!

我刚来到一个地步,我认为这将是很好,在我的代码(方法链抽象&混凝土之间,在仿制药更多的自由)

感谢您的答案!

+0

为什么'IFoo'怎么在意'U'约束?什么是用例? – 2012-03-07 02:44:27

+0

Hi @ M.Babcock在编辑 – 2012-03-07 03:16:55

+0

的第4点回答了解,但不应该'IFoo'将实例化'U'的责任委托给'T '? – 2012-03-07 03:21:17

回答

1

来接近我认为你正在尝试做的唯一事情是

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() 
{ 
} 
+0

Hi @ user375487请看IFoo&T之间的关系 – 2012-03-07 03:17:58

+0

是的,我看到了。尽管如此,你写的几乎是不可能的。您不能通过引用约束参数来指定约束,也不能实现具有对所声明类型的引用的接口。 – 2012-03-07 03:43:52

+0

我看到了......谢谢@ user375487 – 2012-03-07 05:19:40

1

不,你不能这样做,在.NET框架。

看到将泛型类型参数限制为泛型本身没有多大意义。考虑以下类型:

public class StringList : List<string> { } 

StringListList<string>是几乎相同的类型。但是,你能写

Foo<List<string>> 

,而不是

Foo<StringList> 

List<string>已经从泛型类型定义List<>创建的事实是不是真的有关的大多数使用的,除非你的工作关于某种高度反思的行为。

我可以比如看到,你可能希望这样的功能,如果你想要做这样的事情:

public interface GenericTypeConverter<T> where T : <> 
{ 
    T<V> Convert<U,V>(T<U> thing); 
} 

如果你想创建声明函数转换从T<U>T<V>一个转换器接口,任何通用类型T。但是我只能想象如果你从事复杂的代码生成/代码分析。

如果是这种情况,你真正需要的是,你总是可以在运行时检查类型T是通用的,通过调用typeof(T).IsGenericType

+0

Thanks @ d-b我刚刚写了一个我正在尝试做的例子 – 2012-03-07 05:20:30