Brian Mains
Brian Mains

Reputation: 50728

Deep Reflection in .NET

I need to create the ability to drill through an objects properties like two or three deep. For instance, class A has a property reference to class B, which I need to access class C. What is the best way to do this: straight reflection, or maybe using the TypeDescriptor, or something else?

Thanks.

Upvotes: 3

Views: 889

Answers (3)

csharptest.net
csharptest.net

Reputation: 64248

It's not too hard to write. I put a few classes together to deal with this so I could serialize properties of a WinForm. Take a look at this class and the related classes.

http://csharptest.net/browse/src/Library/Reflection/PropertySerializer.cs

Upvotes: 1

John Leidegren
John Leidegren

Reputation: 61057

I you wanna write you own serialization code for whatever reason, you'll be using reflection.

What you do is that you write a recursive method of serlizating a type. You then apply this as you see fit to get the result.

var type = myObjectOfSomeType.GetType();
// now depending on what you want to store
// I'll save all public properties
var properties = type.GetProperties(); // get all public properties
foreach(var p in properties)
{
    var value = p.GetValue(myObjectOfSomeType, null);
    Writevalue(p.Name, value);
}

The implementation of WriteValue have to recognize the built in types and treat them accordingly, that's typical things like string, char, integer, double, DateTime etc.

  • If it encounters a sequence or collection you need to write out many values.
  • If it encounters a non trivial type you'll apply this recursive pattern again.

The end result is a recursive algorithm that traverses your object model and writes out values as it encounters types that I know how to serialize.

However, I do recommend looking into WCF, not for building services, but for serialization. It shipped as part of the .NET 3.0 framework with a new assembly System.Runtime.Serilization and in general is very capable when dealing with serialization and data annotations.

Upvotes: 0

Simon
Simon

Reputation: 34880

If you know the path in a static context (ie the path is always the same) and the properties are accessible (internal or public) you can use dynamic

    [Test]
    public void Foo()
    {
        var a = new A
        {
            B = new B
            {
                C = new C
                {
                    Name = "hello"
                }
            }
        };


        DoReflection(a);
    }

    private void DoReflection(dynamic value)
    {
        string message = value.B.C.Name;
        Debug.WriteLine(message);
    }

Upvotes: 1

Related Questions