Deep reflection in .NET.

I need to create the ability to drill through the properties of objects, for example, two or three. For example, class A has a reference to a property of class B, which I need to refer to class C. What is the best way to do this: direct reflection, or perhaps using TypeDescriptor, or something else?

Thank.

+3
source share
3 answers

Not so hard to write. I put together several classes to handle this so that I can serialize WinForm properties. Take a look at this class and related classes.

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

+1
source

(.. ), ( ),

    [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);
    }
+1

, .

, , serlizating . , , .

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

WriteValue , , string, char, integer, double, DateTime ..

  • , .
  • , .

- , , , , .

However, I recommend looking at WCF, and not at creating services, but at serialization. It comes as part of the .NET 3.0 platform with the new System.Runtime.Serilization assembly and is generally very capable of handling serialization and data annotations.

0
source

Source: https://habr.com/ru/post/1785330/


All Articles