How to get class and property names and values fro

2019-07-31 16:43发布

If I have these two classes:

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

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

Can I use a generic method like this:

public void InitMethod(object classProperty)

To pass in data like this:

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

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

And get the following information from within the method:

  • Class name (ex: "A", "B")
  • Property name (ex: "Id", "Name")
  • Property value (ex: 1, "John")

2条回答
Anthone
2楼-- · 2019-07-31 17:12

In this example you need to pass object to InitMethod not property of that object, maybe it will be OK.

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));
            }
        }
    }
}
查看更多
仙女界的扛把子
3楼-- · 2019-07-31 17:28

Sort of, although it may be more trouble than it is worth.

ASP.Net MVC frequently uses expressions to get at property info in a strongly-typed fashion. The expression doesn't necessarily get evaluated; instead, it is parsed for its metadata.

This isn't specific to MVC; I mention it to cite an established pattern in a Microsoft framework.

Here's a sample that gets a property name and value from an expression:

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

You call it like this (note the expressions being passed):

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

foo = new Foo { Bar = "123456" };
val = EvaluateProperty( o => foo.Bar );
查看更多
登录 后发表回答