-1

can anyone help me?

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.

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.

I get the error

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

Here is the code..

        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();
            }
        }

EDIT

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

1
  • please show the fields of MyItems.Companies and the declaration of CompanyBase. Commented Aug 18, 2011 at 16:16

1 Answer 1

4

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

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.

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

The code sample provided says MyItems.Companies.GetType(), GetType is an instance method not a static method so Companies is a variable, MyItems possibly is as well. The exception message states the type name is MyApp.Companies.Config which is what MyItems.Companies is an instance of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.