从同一(通用)类中调用索引器
public class MyClass<T>
{
public T this[int index]
{
get
{
...
}
set
{
...
}
}
public void MyMethod<T>()
{
int middleIndex = ...;
T value = this[middleIndex ];
...
}
}
由于 MyMethod() 中的语句,代码将无法编译。还有另一种调用索引器的方法吗?
编辑:修改了 MyMethod()
Edit2:编译错误
Error 6 Cannot implicitly convert type 'T [C:\MyClass.cs]' to 'T [C:\MyClass.cs]'
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这对我来说效果很好:
This works fine for me:
调用索引器是可以的,但是它不知道你想要哪个索引。如果将索引设置为 MyMethod 的参数,它将正常工作。
如果您尝试获取当前索引或其他内容,那么您需要存储一个私有变量,将其连接到索引器中并访问它。
您编辑的代码编译得很好...
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...
您的违规代码在这里:
您的类
MyClass
已经有一个泛型类型参数 T,因此MyMethod
上的泛型
是不必要的Your offending code is here:
Your class
MyClass<T>
already has a generic type parameter T, so the generic<T>
onMyMethod
is unnecessary您没有将索引值传递到方法
MyMethod
中 - 您可以发布更多代码吗?看起来好像少了点什么……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...对我来说效果很好:
诚然,我必须将
index
参数引入MyMethod
中,但我假设您想从某个地方...如果这不是您的意思,请澄清。Works fine for me:
Admittedly I had to introduce the
index
parameter intoMyMethod
, but I'm assuming you were wanting to get the index from somewhere... if that's not what you meant, please clarify.