如何在csharp中嵌套泛型类(如果这是适当的名称) [英] how to do nested generic classes (if that's the appropriate name) in csharp

查看:114
本文介绍了如何在csharp中嵌套泛型类(如果这是适当的名称)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建以下类型的类



  public class EnumerableDisposer< IEnumerable< IDisposable> 

但是它不会让我这样声明。我也尝试过:

  public class EnumerableDisposer< T& :IDisposable其中T:IEnumerable< J>其中J:IDisposable 

但是编译器告诉我无法找到类型/命名空间J。 / p>

我要做什么来创建这个类?

解决方案

您需要:

  public class EnumerableDisposer< T,J& :IDisposable 
其中T:IEnumerable< J>不幸的是,不幸的是,这是一个很好的例子,为了包装任何内部类型( IEnumerable ,在你的代码中),你的包装类需要有 code>在通用定义中定义。此外,为了添加 IEnumerable< J> 约束,您需要具有其他类型 T



也就是说,如果你想避免double通用类型规范,你总是可以如下修改:

  public class EnumerableDisposer< T> :IDisposable 
其中T:IDisposable
{
public EnumerableDisposer(IEnumerable< T> enumerable)
{
// ...

这迫使你用 IEnumerable< T> 来构造它,其中T是IDisposable ,具有单个通用类型。因为你通过构造函数有效地添加了 IEnumerable< T> 约束,所以它将像以前的选项一样工作。唯一的缺点是,你需要有通用的施工时间,但给定的名字,我怀疑这将是好的...


I'd like to create a class of the following type

public class EnumerableDisposer<IEnumerable<IDisposable>>

But it won't let me declare it this way. I've also tried:

public class EnumerableDisposer<T> : IDisposable where T : IEnumerable<J> where J : IDisposable

But the compiler tells me that the type/namespace J could not be found.

What is it I have to do to create this class?

解决方案

You need to do:

public class EnumerableDisposer<T, J> : IDisposable 
    where T : IEnumerable<J> where J : IDisposable
{
     // Implement...

Unfortunately, in order to wrap any internal type (IEnumerable<J>, in your code), your "wrapping" class needs to have the type J defined in the generic definition. In addition, in order to add the IEnumerable<J> constraint, you need to have the other type T.

That being said, if you want to avoid the double generic type specification, you could always rework this as follows:

public class EnumerableDisposer<T> : IDisposable 
    where T : IDisposable
{
     public EnumerableDisposer(IEnumerable<T> enumerable)
     { 
        // ...

This forces you to construct it with an IEnumerable<T> where T is IDisposable, with a single generic type. Since you're effectively adding the IEnumerable<T> constraint via the constructor, this will function as well as the previous option. The only downside is that you need to have the generic done at construction time, but given the name, I suspect this will be fine...

这篇关于如何在csharp中嵌套泛型类(如果这是适当的名称)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆