How to get the names and values ​​of classes and properties from an undeclared type

If I have these two classes:

public class A
{
    public int Id { get; set; }
}

public class B
{
    public string Name { get; set; }
}

Is it possible to use the general method as follows:

public void InitMethod(object classProperty)

To transfer data as follows:

var a = new A() { Id = 1 };
var b = new B() { Name = "John" };

InitMethod(a.Id);
InitMethod(b.Name);

And get the following information from the method:

  • Class name (for example: "A", "B")
  • Property name (for example: "Identifier", "Name")
  • Property value (ex: 1, "John")
+1
source share
2 answers

Grade, although this may be more of a problem than it costs.

ASP.Net MVC often uses expressions to retrieve property information in a strongly typed way. The expression is not necessarily evaluated; instead, it is parsed for its metadata.

MVC; , Microsoft.

, :

// the type being evaluated
public class Foo
{
    public string Bar {
        get;
        set;
    }
}

// method in an evaluator class
public TProperty EvaluateProperty<TProperty>( Expression<Func<Foo, TProperty>> expression ) {
    string propertyToGetName = ( (MemberExpression)expression.Body ).Member.Name;

    // do something with the property name

    // and/or evaluate the expression and get the value of the property
    return expression.Compile()( null );
}

( ):

var foo = new Foo { Bar = "baz" };
string val = EvaluateProperty( o => foo.Bar );

foo = new Foo { Bar = "123456" };
val = EvaluateProperty( o => foo.Bar );
+2

InitMethod not , , .

class Program
{
    static void Main(string[] args)
    {
        InitMethod(new A() { Id = 100 });
        InitMethod(new B() { Name = "Test Name" });

        Console.ReadLine();
    }

    public static void InitMethod(object obj)
    {
        if (obj != null)
        {
            Console.WriteLine("Class {0}", obj.GetType().Name);
            foreach (var p in obj.GetType().GetProperties())
            {
                Console.WriteLine("Property {0} type {1} value {2}", p.Name, p.GetValue(obj, null).GetType().Name, p.GetValue(obj, null));
            }
        }
    }
}
+1

All Articles