我需要找到以下代码的等价物,以便在便携式库中使用: Public Overridable Function GetPropertyValue(ByVal p_propertyName As String) As Object Dim bf As System.Reflection.BindingFlags bf = Reflection.BindingFlags.IgnoreCas
Public Overridable Function GetPropertyValue(ByVal p_propertyName As String) As Object
Dim bf As System.Reflection.BindingFlags
bf = Reflection.BindingFlags.IgnoreCase Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic
Dim propInfo As System.Reflection.PropertyInfo = Me.GetType().GetProperty(p_propertyName, bf)
Dim tempValue As Object = Nothing
If propInfo Is Nothing Then
Return Nothing
End If
Try
tempValue = propInfo.GetValue(Me, Nothing)
Catch ex As Exception
Errors.Add(New Warp10.Framework.BaseObjects.BaseErrorMessage(String.Format("Could not Get Value from Property {0}, Error was :{1}", p_propertyName, ex.Message), -1))
Return Nothing
End Try
Return tempValue
End Function
BindingFlags似乎不存在. System.Reflection.PropertyInfo是一个有效的类型,但我无法弄清楚如何填充它.有什么建议?
对于Windows 8 / Windows Phone 8,许多此Reflection功能已移至新的TypeInfo类.您可以找到更多信息 in this MSDN doc.有关包括运行时属性(包括例如继承的属性)的信息,您也可以使用新的 RuntimeReflectionExtensions class(可以通过LINQ简单地进行过滤).虽然这是C#代码(我的道歉:)),但这里使用这个新功能是完全相同的:
public class TestClass
{
public string Name { get; set; }
public object GetPropValue(string propertyName)
{
var propInfo = RuntimeReflectionExtensions.GetRuntimeProperties(this.GetType()).Where(pi => pi.Name == propertyName).First();
return propInfo.GetValue(this);
}
}
如果您只关心在类本身声明的属性,那么此代码甚至更简单:
public class TestClass
{
public string Name { get; set; }
public object GetPropValue(string propertyName)
{
var propInfo = this.GetType().GetTypeInfo().GetDeclaredProperty(propertyName);
return propInfo.GetValue(this);
}
}
