how to do nested generic classes (if that's the appropriate name) in csharp

后端 未结 3 880
北恋
北恋 2020-12-17 23:38

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

public class EnumerableDisposer>

But it won\'t let m

3条回答
  •  孤城傲影
    2020-12-18 00:03

    You need to do:

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

    Unfortunately, in order to wrap any internal type (IEnumerable, 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 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 : IDisposable 
        where T : IDisposable
    {
         public EnumerableDisposer(IEnumerable enumerable)
         { 
            // ...
    

    This forces you to construct it with an IEnumerable where T is IDisposable, with a single generic type. Since you're effectively adding the IEnumerable 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...

提交回复
热议问题