Having trouble wrapping my head around using expressions in c#
I am trying to do a simple expression example of getting the name of a property. This is meant as a simple tutorial to walk myself through wrapping my head around C# Expressions.
I have the following code:
public class TestClass
{
public string TestProperty { get; set; }
}
class Program
{
static void Main(string[] args)
{
TestClass test = new TestClass();
string name = GetPropertyName(() => test.TestProperty);
Console.WriteLine("Property name is: ");
Console.ReadLine();
}
public string GetPropertyName(Expre开发者_开发百科ssion<Func<object, object>> expression)
{
var memberExp = expression.Body as MemberExpression;
if (memberExp == null)
throw new InvalidOperationException("Not a member expression");
return memberExp.Member.Name;
}
}
This produces 2 issues:
1) When is tart typing string name = GetPropertyName
Intellisense doesn't actually show my GetPropertyName()
method.
2) The () => test.TestProperty
gives a compile error of Delegate 'System.Func<object,object>' does not take 0 arguments
I have been trying to use http://marlongrech.wordpress.com/2008/01/08/working-with-expression-trees-part-1/ and http://jagregory.com/writings/introduction-to-static-reflection/ as tutorials/references, but I am definitely not understanding something.
First, System.Func<object,object>
means your lambda expression takes an argument of type object and returns an object, so you're going to have an expression like (arg) => test.PropertyName
. If you don't want to take an input parameter, just use System.Func<object>
.
Second, you're not seeing your GetPropertyName method in Intellisense because Main is a static
method. Either make an instance of your Program object and call it from there, or declare GetPropertyName as static
too.
精彩评论