Assumptions
Suppose I have a class with a property:
class ClassWithProperty
{
public string Prop { get; private set; }
public ClassWithProperty(string prop)
{
this.Prop = prop;
}
}
And now suppose I created an instance of this class:
var test = new ClassWithProperty("test value");
What I want
I want this to be printed on the console:
Prop = 'test value'
Piece of cake! I use this code to generate the desired output:
Console.WriteLine("Prop = '{1}'", test.Prop);
Problem
I violate DRY because "Prop" appears twice in the code above. If I reorganize the class and change the name of the property, I must also change the string literal. There is also a lot of template code if I have a class with many properties.
Proposed solution
string result = buildString(() => c.Prop);
Console.WriteLine(result);
Where the buildString method is as follows:
private static string buildString(Expression<Func<string>> expression)
{
MemberExpression memberExpression = (MemberExpression)expression.Body;
string propertyName = memberExpression.Member.Name;
Func<string> compiledFunction = expression.Compile();
string propertyValue = compiledFunction.Invoke();
return string.Format("{0} = '{1}'", propertyName, propertyValue);
}
Question
, , "" , . ? , - ?
Edit
Manu (. ) :
static public IEnumerable<string> ListProperties<T>(this T instance)
{
return instance.GetType().GetProperties()
.Select(p => string.Format("{0} = '{1}'",
p.Name, p.GetValue(instance, null)));
}
.
: , - ? ... ?
2
.
. , , ( LINQ'd):
public static IEnumerable<string> BuildString(this object source)
{
return from p in source.GetType().GetProperties()
select string.Format("{0} = '{1}'", p.Name, p.GetValue(source, null));
}
:
new { c.Prop }.BuildString().First()
, ( , ). , , , , (. ).