答案 0 :(得分:0)
Expression.PropertyOrField
方法使用GetProperty(string,BindingFlags)
来查找属性。此函数似乎不实现名称隐藏,而相应的GetField(string,BindingFlags)
实现。
您需要使用GetProperties
并选择所需的属性,然后使用Expression.Property
的{{1}}重载。
答案 1 :(得分:0)
对于那些感兴趣的人...
它在线失败
GetType(Inherited(Of String)).GetProperty("Prop1")
Imports System.Linq.Expressions
Imports NUnit.Framework
<TestFixture> Public Class ExpressionTEst
<Test> Public Sub GetOvrriddenProperyInExpression()
Dim ex = Expression.PropertyOrField(Expression.Constant(Nothing, GetType(Inherited(Of String))), "field1")
Dim ex2 = Expression.PropertyOrField(Expression.Constant(Nothing, GetType(Inherited(Of String))), "t2")
GetType(Inherited(Of String)).GetField("field1")
GetType(Inherited(Of String)).GetProperty("Prop1")
Dim ex3 = Expression.PropertyOrField(Expression.Constant(Nothing, GetType(Inherited(Of String))), "Prop1")
End Sub
Public Class Base
Public field1 As Object
Public Property Prop1 As Object
Public Overridable Property t2 As String
End Class
Public Class Inherited(Of T)
Inherits Base
Public Overrides Property t2 As String
Get
Return MyBase.t2
End Get
Set(value As String)
MyBase.t2 = value
End Set
End Property
Public Shadows field1 As T
Public Shadows Property Prop1 As T
End Class
结束班
因为@NetMage和@IvanStoev说GetField与GetProperty的不一致
这段代码解决了它......有点
Expression memberValue = null;
if (m.MemberType == MemberTypes.Property)
{
PropertyInfo propInfo = null;
foreach(var p in m.DeclaringType.GetProperties())
{
if (p.Name == m.Name)
{
//Just pick the first one.
propInfo = p;
break;
}
}
memberValue = Expression.Property(Expression.Convert(valueObject, objType), propInfo);
}
else
{
memberValue = Expression.Field(Expression.Convert(valueObject, objType), m.Name);
}