My Code in C# is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace cs
{
public class TreeNode<T> : IEnumerable
{
}
And I got error here:
Error 1 Using the generic type
'System.Collections.Generic.IEnumerable<T>'
requires 1 type arguments
Interface IEnumerable
is declared in System.Collections
, so following should be added:
using System.Collections;
There is also a similar interface, IEnumerable<T>
, which is a generic version of IEnumerable and that one is declared in System.Collections.Generic
and that is why Visual Studio gives you such a mysterious error.
There are two "versions" of IEnumerable
.
One is the nongeneric System.Collections.IEnumerable
. This is provided mostly for backwards compatibility. I can't really think of a good reason to make new classes directly inherit from it.
The other is the generic one, System.Collections.Generic.IEnumerable<T>
. This implements IEnumerable
as well, so it's a better choice in all cases.
When an interface has a generic overload, you need to specify that generic type parameter. In your case,
public class TreeNode<T> : IEnumerable<T>
It's worth noting that when you implement this, you'll need to implement two methods:
Enumerator<T> GetEnumerator(); // From IEnumerable<T>
Enumerator IEnumerable.GetEnumerator(); // From IEnumerable
It's not too unusual too return this.GetEnumerator()
from the second one, since again, it's provided mostly as backwards-compatibility. You always want those two enumerators to return the same data, so that's a nice and easy solution.
You should use:
System.Collections.IEnumerable
instead of
IEnumerable
or
System.Collections.Generic.IEnumerable
You either need to
IEnumerable
which is located in System.Collection
namespace (which you did not include) Sample for generic version:
class TreeNode<T> : IEnumerable<T>
{....}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With