验证对象是否具有特定属性 [英] Verify that an object has a certain property

查看:24
本文介绍了验证对象是否具有特定属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此处找到了 C# 代码一个>

所以我尝试了

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

但是它在 type.GetMethod(propertyy) 处抛出一个错误,说 类型 'System.Reflection.MethodInfo' 的值不能转换为 'Boolean'."

But it throws an error at type.GetMethod(propertyy) saying "Value of type 'System.Reflection.MethodInfo' cannot be converted to 'Boolean'."

怎么办?

推荐答案

首先,C# 代码检查是否存在方法,而不是属性.二、C#代码比较返回null:

First, C# code checks for presence of a method, not a property. Second, C# code compares return to 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

编辑要检查字段,请按如下方式更改方法:

EDIT To check for fields, change the method as follows:

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

这篇关于验证对象是否具有特定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆