how to do nested generic classes (if that's th

2019-01-25 12:11发布

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?

3条回答
Root(大扎)
2楼-- · 2019-01-25 12:48

you need to definie J.

eg

public class EnumerableDispose<T, J> : IDisposable
   where T : IEnumerable<T>
   where J : IDisposable

better would be:

public class EnumerableDispose<T> : IEnumerable<T>, IDisposable
    where T : IDisposable
{
    public EnumerableDispose(IEnumerable<T> source)
    {
        // TODO: implement
    }
}
查看更多
淡お忘
3楼-- · 2019-01-25 12:55

You can do this by adding an extra J type parameter:

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

Note that these T and J parameters are independent of any parameters in the outer class, even if they have the same names.

查看更多
女痞
4楼-- · 2019-01-25 13:04

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...

查看更多
登录 后发表回答