Using obect's property names in strongly type

2019-08-15 03:48发布

Is there a way (in c# .Net 4.0) to provide object property name in strongly type manner? For instance, if we have an object Person

Public class Person{
    public string Name { get; set; }
    public int Age { get; set; }
    }

And I want to sent to some other method the parameters Name, Age property name but not as string but strongly type:

SomeMethodThatWantToKnowKeys(Person.Name,Person.Age);

What I want to achieve is that if someone change the property name, he will have to change they property names he is sending to 'SomeMethodThatWantToKnowKeys'. Maybe reflection? A better way will be without updating the object itsef or creating an instance of it.

2条回答
甜甜的少女心
2楼-- · 2019-08-15 04:02

Okay so while there are some ugly hacks there is a much better and clearner solution. This problem is because the abstraction is not in place.

What is a name? A String? It could be an int, double, char, float....anything...you do not really care about the underlying type. You care about the concept or notion of a name. I know this is a bit more deep, but this experience will help you with good design.

Here is what I suggest for now, but personally I might go do more.

public class PersonName
{
    public String Name { get; set; }
}

public class PersonAge
{
    public int Age {get;set;}
}

public class Person
{ 
    public PersonName PersonName {get;set;}
    public PersonAge PersonAge {get;set;}
}

So now your method signature is:

    SomeMethodThatWantToKnowKeys(PersonName,PersonAge);

Type safety is an amazing thing!

查看更多
Summer. ? 凉城
3楼-- · 2019-08-15 04:11

If I understand what you want, you could use expressions:

void SomeMethod<T>(Expression<Func<T>> expr)
{
    var memberExpr = expr.Body as MemberExpression;
    Console.WriteLine("{0}: {1}", memberExpr.Member.Name, expr.Compile()());
}

var person = new { Name = "John Doe", Age = 10 };
SomeMethod(() => person.Name); // prints "Name: John Doe"
SomeMethod(() => person.Age);  // prints "Age: 10"
查看更多
登录 后发表回答