2012-02-22 10 views
5

encontré C# código para ello hereVerificar que un objeto tiene una cierta propiedad

Así que intentó

Public Function checkProperty(ByVal objectt As Object, ByVal propertyy As String) As Boolean 
    Dim type As Type = objectt.GetType 
    Return type.GetMethod(propertyy) 
End Function 

Pero lanza un error en type.GetMethod(propertyy) diciendo "Value of type 'System.Reflection.MethodInfo' cannot be converted to 'Boolean'."

¿Qué hacer?

Respuesta

15

primera, C cheques # de código para la presencia de un método , no una propiedad. En segundo lugar, el código C# compara retorno a null:

Public Function checkProperty(ByVal objectt As Object, ByVal propertyy As String) As Boolean 
    Dim type As Type = objectt.GetType 
    Return type.GetProperty(propertyy) IsNot Nothing 
End Function 

EDITAR Para comprobar si hay campos, cambie el método de la siguiente manera:

Public Function checkField(ByVal objectt As Object, ByVal fieldName As String) As Boolean 
    Dim type As Type = objectt.GetType 
    Return type.GetField(fieldName) IsNot Nothing 
End Function 
+0

'Volver type.GetProperty (propertyy) IsNot Nothing' siempre se vuelve falso, incluso si la propiedad sin duda existe. Intenté 'checkProperty (test," id ")' y 'checkProperty (test," test ")'. El primero debería ser cierto, pero no lo es. 'MsgBox (type.Name)' indica correctamente que la clase encontrada es del tipo "CTest". 'CTest' tiene dos propiedades:' Public id as integer' y 'Public name as string' – natli

+1

@natli Tanto' id' como 'name' son * variables de instancia *, no * propiedades *. Ver mi actualización – dasblinkenlight

+0

Error de principiante de mi parte, ¡gracias! – natli

4

que está devolviendo el MethodInfo lugar y usted puede simplemente el cambio de la siguiente manera:

Public Function checkProperty(ByVal objectt As Object, ByVal propertyy As String) As Boolean 
    Dim type As Type = objectt.GetType 
    Return type.GetMethod(propertyy) IsNot Nothing 
End Function 
0

Está intentando devolver el type.GetMethod (propert yy), donde su código de ejemplo devuelve el resultado de evaluar si ese método es nulo o no.

tratar Return type.GetMethod(propertyy) isnot nothing

Cuestiones relacionadas