Calling indexer from within the same (generic) class
public class MyClass<T>
{
public T this[int index]
{
get
{
...
}
set
{
...
}
}
public void MyMethod<T>()
{
int middleIndex = ...;
T value = this[middleIndex ];
...
}
}
The code won't compile because of the statement in MyMethod(). Is there another way of calling the indexer ?
Edit: Modified MyMethod()
Edit2: Compilation error
Error 6 Cannot implicitly convert开发者_运维知识库 type 'T [C:\MyClass.cs]' to 'T [C:\MyClass.cs]'
Thanks.
Works fine for me:
public class MyClass<T>
{
public T this[int index]
{
get
{
return default(T);
}
set
{
}
}
public void MyMethod(int index)
{
T value = this[index];
}
}
Admittedly I had to introduce the index
parameter into MyMethod
, but I'm assuming you were wanting to get the index from somewhere... if that's not what you meant, please clarify.
This works fine for me:
public class MyClass<T>
{
List<T> _items = new List<T>();
public T this[int index]
{
get
{
return _items[index];
}
}
public void MyMethod()
{
T value = this[2];
}
}
Calling the indexer is fine, but it doesn't know which index you want. If you make index a parameter of MyMethod it will work fine.
If you're trying to get the current index or something then you need to store a private variable, wire it up in your indexer and access that.
Your edited code compiles fine...
public class MyClass<T>
{
public T this[int index]
{
get
{
...
}
set
{
...
}
}
public void MyMethod()
{
int middleIndex = ...;
T value = this[middleIndex ];
...
}
}
you're not passing in a value for the index into the method MyMethod
- can you post a little more code? It looks like something is missing...
Your offending code is here:
public void MyMethod<T>()
Your class MyClass<T>
already has a generic type parameter T, so the generic <T>
on MyMethod
is unnecessary
精彩评论