dimanche 29 novembre 2020

Linq Reflection Expression throws exception on property of proprety

I'm trying to make functions with Linq Expressions arguments and am stuck on a problem.

Here's my test function:

public static void OutputField(Person p, Expression<Func<Person, string>> outExpr)
{
    var expr = (MemberExpression)outExpr.Body;
    var prop = (PropertyInfo)expr.Member;
    string v = prop.GetValue(p, null).ToString();
    Console.WriteLine($"value={v}");
}

If I define a Person object as

public class Person
{
    public PersonName Name { get; set; }
    public string City { get; set; }
}

public class PersonName
{
    public string First { get; set; }
    public string Last { get; set; }
}

and try to use it this way

Person person = new Person
{
    Name = new PersonName { First = "John", Last = "Doe" },
    City = "New York City"
};

OutputField(person, m => m.City);
OutputField(person, m => m.Name.First);

The output of the property City works, but the output of the property First of the property Name throws a System.Reflection.TargetException: 'Object does not match target type.' error. How do I make my test function work?





Aucun commentaire:

Enregistrer un commentaire