我需要找到以下代码的等价物,以便在便携式库中使用:
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是一个有效的类型,但我无法弄清楚如何填充它。有什么建议吗?
答案 0 :(得分:7)
对于Windows 8 / Windows Phone 8,很多此反射功能已移至新的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);
}
}