views:

199

answers:

2

I am looking at a pattern implemented in Java and have some questions about how it aligns to (can be ported to) C#.

Java:

class Foo
{
    private Class someClass;
    ...
}

class Bar
{
    private Field some Field;
}

First, Class stores an instance of a domain object. It looks like Java exposes reflection methods on the type which are used to access fields on the object through reflection. What would type would be synonymous in C#? Would I use object and then use MethodInfo or is there a better way?

Second, Field is type in the framework and is assigned by using:

someClass.getDeclaredField(fieldName)

Is there a parallel in the .NET framework i should use?

Right now I created a custom object in place of the Class in Foo, and I created a custom object for Field. Is there a preferred way to do this?

+5  A: 

You may take a look at the FieldInfo type and GetField method.

Code might look something among the lines:

class Foo
{
    public Type someClass;
    ...
}

class Bar
{
    private FieldInfo some_Field;

    public Assign(string fieldName)
    {
        Foo foo = new Foo();
        some_Field = foo.someClass.GetField(fieldName);
    }
}
Darin Dimitrov
A: 

You may also get the value of the field by using:

 foo.GetType().GetField("name").GetValue(foo).ToString()

In this example, we assume class foo has a field named "name". What does this help? Well think it as this way:

private string getValueOfUnknownField(string fieldName)
{
    return(foo.GetType().GetField(fieldName).GetValue(foo).ToString());
}

Even if you change class foo and add new fields to it, you don't need to change getValueOfUnknownField method.