Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...