C#:使用反射访问类中的所有字段,返回错误 [英] C#: Using reflection to get access to all fields within a class, returns error

查看:52
本文介绍了C#:使用反射访问类中的所有字段,返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我吗?

我编写了一些反射代码,它似乎运行良好,但在尝试将this"传递给 GetValue 时出现错误.

I have some reflection code that i have written and it seems to work well but it gives me an error when trying to pass in "this" to the GetValue.

我有点卡住了,我认为问题是我在 frmMain 中运行反射代码,而 AbCCompany 是在另一个项目中定义的,但我有一个参考.

I am a little stuck, i think the problem is that i am running the reflection code in frmMain adn the AbCCompany is defined in another project but i have a reference.

我收到错误

在类型MyApp.Companies.Config"上定义的字段AbcCompany"不是类型为MyApp.frmMain"的目标对象上的字段.

Field 'AbcCompany' defined on type 'MyApp.Companies.Config' is not a field on the target object which is of type 'MyApp.frmMain'.

这是代码..

        var companies = MyIems.Companies.GetType().GetFields();


        foreach (var list in companies )
        {

            List<CompanyBase> thisCompanyCollection = (List<CompanyBase>)list.GetValue(this);
            foreach (var company in thisCompanyCollection )
            {
                Console.WriteLine();
            }
        }

编辑

我忘了提到公司​​"内部有很多列表,其中 xxx 是一个类.所有类都继承自 CompanyBase.即 AbcCompany

I forgot to mention that Inside "Companies" is lots of List where xxx is a class.. all classes inherit from CompanyBase. i.e AbcCompany

推荐答案

不是将 this 传递给 GetValue,而是需要传递 MyApp 的实例.公司.配置.

Instead of passing in this to GetValue you need to pass an instance of MyApp.Companies.Config.

如果您查看文档,你可以看到你得到的异常是因为 obj 参数不是当前字段声明的类型(或继承自它).

If you look at the documentation, you can see that the exception your getting is because the obj parameter isn't of the type (or inherits from it) that the current field is declared on.

假设 MyApp.Companies.Config 有一个无参数的构造函数,以下应该可以工作:

Assuming that MyApp.Companies.Config has a parameterless constructor, the following should work:

var type = MyItems.Companies.GetType();

var instance = type.GetConstructor(System.Type.EmptyTypes).Invoke(null);

foreach(var list in type.GetFields())
{
    List<CompanyBase> thisCompanyCollection = (List<CompanyBase>)list.GetValue(instance);
    foreach(var company in thisCompanyCollection)
    {
        Console.WriteLine(company);
    }
}

这篇关于C#:使用反射访问类中的所有字段,返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆