我正在编写一些代码,其最终目的是让您使用属性表达式来设置属性值,其语法类似于将变量作为out或ref参数传递。
类似于以下内容:
public static foo(()=>Object.property, value);
Run Code Online (Sandbox Code Playgroud)
并且将为Object.Property分配value的值。
我正在使用以下代码来获取属性的所属对象:
public static object GetOwningObject<T>(this Expression<Func<T>> @this)
{
var memberExpression = @this.Body as MemberExpression;
if (memberExpression != null)
{
var fieldExpression = memberExpression.Expression as MemberExpression;
if (fieldExpression != null)
{
var constExpression = fieldExpression.Expression as ConstantExpression;
var field = fieldExpression.Member as FieldInfo;
if (constExpression != null) if (field != null) return field.GetValue(constExpression.Value);
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
因此,当在()=> Object.Property之类的属性表达式上使用时,它将返回'Object'的实例。我对使用属性表达式有些陌生,似乎有许多不同的方法可以完成任务,但是我想扩展到目前为止的内容,以便给定一个表达式()=> Foo.Bar.Baz将给予律师,而不是Foo。我总是想要表达式中的最后一个包含对象。
有任何想法吗?提前致谢。
你要做的是遍历属性链到最外层的对象。下面的示例是不言自明的,表明扩展方法适用于链式字段和属性:
class Foo
{
public Bar Bar { get; set; }
}
class Bar
{
public string Baz { get; set; }
}
class FooWithField
{
public BarWithField BarField;
}
class BarWithField
{
public string BazField;
}
public static class LambdaExtensions
{
public static object GetRootObject<T>(this Expression<Func<T>> expression)
{
var propertyAccessExpression = expression.Body as MemberExpression;
if (propertyAccessExpression == null)
return null;
//go up through property/field chain
while (propertyAccessExpression.Expression is MemberExpression)
propertyAccessExpression = (MemberExpression)propertyAccessExpression.Expression;
//the last expression suppose to be a constant expression referring to captured variable ...
var rootObjectConstantExpression = propertyAccessExpression.Expression as ConstantExpression;
if (rootObjectConstantExpression == null)
return null;
//... which is stored in a field of generated class that holds all captured variables.
var fieldInfo = propertyAccessExpression.Member as FieldInfo;
if (fieldInfo != null)
return fieldInfo.GetValue(rootObjectConstantExpression.Value);
return null;
}
}
[TestFixture]
public class Program
{
[Test]
public void Should_find_root_element_by_property_chain()
{
var foo = new Foo { Bar = new Bar { Baz = "text" } };
Expression<Func<string>> expression = () => foo.Bar.Baz;
Assert.That(expression.GetRootObject(), Is.SameAs(foo));
}
[Test]
public void Should_find_root_element_by_field_chain()
{
var foo = new FooWithField { BarField = new BarWithField { BazField = "text" } };
Expression<Func<string>> expression = () => foo.BarField.BazField;
Assert.That(expression.GetRootObject(), Is.SameAs(foo));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
906 次 |
| 最近记录: |