本文介绍了如何通过反射访问Generic.List的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我通过的对象是 List< X>



在我的课上,我试图通过反射访问对象索引但是我不能!



示例:

这个班的作品我只写下了我想向你展示的部分,我需要帮助。

  class MyClass 
{
private object _recordSet;
public object RecordSet
{
get {return _recordSet; }
set {_recordSet = value; }

$ b public string Draw()
{
system.reflection.Assembly asem = system.reflection.Assembly.getAssembly(_dataSource.GetType());

对象实例;

instance = asem.CreateInstance(_dataSource.GetType()。UnderlyingSystemType.FullName);

//访问de我的列表计数
int recordcount = int.Parse(_dataSource.GetType()。GetProperty(Count)。GetValue(_dataSource,null));

//我需要为
做(int cont = 0; cont< recordCount; cont ++)
{
_dataSource [cont] .Name; //< - 这部分不工作!因为我不能直接访问索引....怎么办? ???




解决方案

如果您使用反射(因此很多 object ),为什么不只是投射为 IList (非泛型)而不是?



  IList list = (IList的)actualList; 
object foo = list [17];

另外 - 对于您的原始代码,使用 Count ,你不是指 int.Parse - 你应该投射(因为我们期望 Count 是一个 int )。


ok, ive a class and i pass an object as property.

the object that i pass is a List<X>

in my class im trying to access the Object index by reflection BUT I CAN'T!!!

Example:

this class works i just wrote down the part i want to show you and i need help.

class MyClass
{
    private object _recordSet;
    public object RecordSet
    {
        get { return _recordSet; }
        set { _recordSet = value; }
    }

    public string Draw()
    {
        system.reflection.Assembly asem = system.reflection.Assembly.getAssembly(_dataSource.GetType());

        object instance;

        instance = asem.CreateInstance(_dataSource.GetType().UnderlyingSystemType.FullName);

        //to access de Count of my List
        int recordcount = int.Parse(_dataSource.GetType().GetProperty("Count").GetValue(_dataSource,null));

        //i need to do a 
        for(int cont = 0; cont < recordCount; cont++)
        {
            _dataSource[cont].Name; // <-- THIS PART IS NOT WORKING!!! because i cant access the Index Directly.... WHAT TO DO!! ???
        }
    }
}
解决方案

If you are using reflection (and hence lots of object), why not just cast as an IList (non-generic) instead?

i.e.

IList list = (IList)actualList;
object foo = list[17];

Also - for your original code with Count, you don't mean int.Parse - you should just cast (since we expect Count to be an int).

这篇关于如何通过反射访问Generic.List的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 13:46