AddOptional<tblObject>(x =>x.Title, objectToSend.SupplementaryData);
private static void AddOptional<TType>(Expression<Func<TType,string>> expr, Dictionary<string, string> dictionary)
{
string propertyName;
string propertyValue;
Expression expression = (Expression)expr;
while (expression.NodeType == ExpressionType.Lambda)
{
expression = ((LambdaExpression)expression).Body;
}
}
在上面的代码中我想得到属性标题的实际值,而不是属性名称,是否可能?
答案 0 :(得分:3)
private static void Main(string[] args)
{
CompileAndGetValue<tblObject>(x => x.Title, new tblObject() { Title = "test" });
}
private static void CompileAndGetValue<TType>(
Expression<Func<TType, string>> expr,
TType obj)
{
// you can still get name here
Func<TType, string> func = expr.Compile();
string propretyValue = func(obj);
Console.WriteLine(propretyValue);
}
但是,你必须意识到这可能会很慢。您应该测量它在您的情况下的表现。
如果您不想传递您的对象:
private static void Main(string[] args)
{
var yourObject = new tblObject {Title = "test"};
CompileAndGetValue(() => yourObject.Title);
}
private static void CompileAndGetValue(
Expression<Func<string>> expr)
{
// you can still get name here
var func = expr.Compile();
string propretyValue = func();
Console.WriteLine(propretyValue);
}