Please see the code below. I want to create a Unit Test and use intellisense (for refactoring and compile time error purposes) to get me the name of a static property in a static class. I want this because I am loading an assembly from a file later on and need to get the value of a static property in a static class using reflection.
I know how it could be done using LINQ, see the Hat
class below. But how would I get the LastWashed
property of the Underwear
class in a similar matter?
public class Test
{
public static void TestFunction()
{
String NameOfColorPropertyOfHat = Hat.GetPropertyName(H => H.color);
//How would I get the name of the property of the static class
}
}
public static class Underwear
{
public static DateTime LastWashed
{
get
{
return DateTime.Now.Subtract(TimeSpan.FromDays(3));
}
}
}
public class Hat
{
public Color color
{
get
{
return Color.Green;
}
}
public static string GetPropertyName(Expression<Func<Hat, object>> expression)
{
if (expression.Body is MemberExpression)
{
return ((MemberExpression)expression.Body).Member.Name;
}
else
{
var op = ((UnaryExpression)expression.Body).Operand;
return ((MemberExpression)op).Member.Name;
}
}
}