如何在 C# .net 2.0 中使用反射访问索引器每个成员的属性
我有以下方法:
object GetIndexer()
该方法的结果是类型的索引器:
SomeCollection<T>
现在 T 可以是任何东西,因为我知道每个 T 都扩展了类型 Y。
我尝试强制转换
SomeCollection<Y> result= (SomeCollection<Y>) GetIndexer()
它不起作用。
我需要知道的是如何使用反射访问索引器 SomeCollection 中每个项目的属性?
I have the following method:
object GetIndexer()
The result of the method is an indexer of the type:
SomeCollection<T>
Now T can be anything, by I know that each T extends the type Y.
I tried casting
SomeCollection<Y> result= (SomeCollection<Y>) GetIndexer()
It didn't work.
What I need to know is how to access a property for each item in the indexer SomeCollection using Reflection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对每个项目使用
GetType()
,然后调用 GetProperties() 或 GetProperty(propertyName) 获取属性信息。这样,您就可以调用GetValue()
传入您的对象。一个例子:
Use
GetType()
for each item, then call either GetProperties() or GetProperty(propertyName) to obtain the PropertyInfo. With this, you then callGetValue()
passing in your object.An example:
一些上下文会有所帮助,但听起来你已经有了类似的东西,
在这种情况下,为什么不只是
那样,不需要演员。
但我对您使用“索引器”一词感到有点困惑。 C# 的索引器是一种重载类型的 [] 运算符的方法,以便您可以执行以下操作:
它们的定义如下:
SomeCollection
类型的对象不是一个索引器,它是一个集合。Some context would be helpful, but it sounds like you've got something like
In that case, why not just
That way, no cast is required.
But I am a little confused by your use of the term 'indexer'. An indexer for a C# is a way of overloading the [] operator for a type, so that you can do things like:
They are defined like so:
An object of type
SomeCollection<Y>
isn't an indexer, it's a collection.SomeCollection
是否可枚举?如果是这样,您可以这样做或者等到 C# 4.0 为我们提供更多协变和逆变选项。
Is
SomeCollection<T>
enumerable? If so you could doOr wait until C# 4.0 gives us more covariance and contravariance options.
循环遍历列表就是枚举的过程。使用枚举器是最简单的。也就是说(在 C# 中):任何实现
IEnumberable
的东西。如果您尝试循环的对象是您自己创建的对象之一,我建议实现 IEnumberable。如果不是,您能否提供有关此特定第 3 方对象的更多信息?也许还有其他人也需要以这种方式使用它,也许我们中的一个人可以在网上找到他们的作品。
To loop through a list is the process of enumeration. It is easiest with an Enumerator. That is (in C#): anything that implements
IEnumberable
.If the object you are trying to loop through is one of your own making, I recommend implementing IEnumberable. If it isn't, can you give more info about this specific 3rd party object? Maybe there are others who've also needed to use it in this way and maybe their work can be found by one of us online.