5

我想创建一个函数,我可以在其中传入任意对象并检查它是否具有具有特定值的特定属性。我试图使用反射来做到这一点,但反射仍然让我有点困惑。我希望有人能指出我正确的方向。

这是我尝试的代码,但显然它不起作用:

    public static bool PropertyHasValue(object obj, string propertyName, string propertyValue)
{
    try
    {
        if(obj.GetType().GetProperty(propertyName,BindingFlags.Instance).GetValue(obj, null).ToString() == propertyValue)
        {
            Debug.Log (obj.GetType().FullName + "Has the Value" + propertyValue);
            return true;    
        }

        Debug.Log ("No property with this value");
        return false;
    }
    catch
    {
        Debug.Log ("This object doesnt have this property");
        return false;
    }

}
4

4 回答 4

5

您将需要BindingFlagsType.GetProperty方法调用中指定更多内容。您可以使用一个|字符和其他标志来执行此操作,例如BindingFlags.Public. 其他问题不是从您的调用中检查空obj参数或空结果。PropertyInfo.GetValue

为了在你的方法中更明确,你可以这样写,然后在你认为合适的地方折叠。

public static bool PropertyHasValue(object obj, string propertyName, string propertyValue)
{
    try
    {
        if(obj != null)
        {
            PropertyInfo prop = obj.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
            if(prop != null)
            {
                object val = prop.GetValue(obj,null);
                string sVal = Convert.ToString(val);
                if(sVal == propertyValue)
                {
                    Debug.Log (obj.GetType().FullName + "Has the Value" + propertyValue);
                    return true;    
                }
            }
        }

        Debug.Log ("No property with this value");
        return false;
    }
    catch
    {
        Debug.Log ("An error occurred.");
        return false;
    }
}

在我看来,您应该接受propertyValueobject平等地比较对象,但这会表现出与原始样本不同的行为。

于 2012-10-02T20:13:33.003 回答
2

在这里回答这个问题为时已晚。但我正在寻找同样的问题,并用LINQand以更简洁的方式解决了它Reflection。因此,如果您对LINQ. 你可以像这样得到它。

String propertyValue = "Value_to_be_compared";

Bool Flag = YourObject.GetType().GetProperties().Any(t => t.GetValue(objEmailGUID, null).ToString().Contains(propertyValue));

if(Flag)
{
  //spread love if true
}

代码将检查您对象的任何属性是否包含Value_to_be_compared

如果您想匹配确切的值,那么您可以选择:

Bool Flag = YourObject.GetType().GetProperties().Any(t => t.GetValue(objEmailGUID, null).ToString() == propertyValue);
于 2013-12-02T07:33:52.473 回答
1

检索成员时,除了指定实例/静态之外,您还必须指定 Public/NonPublic:

例如,要检索公共属性,您将使用:

GetProperty(propertyName,BindingFlags.Instance | BindingFlags.Public)

要检索所有属性,您必须同时检索 Public 和 NonPublic。

于 2012-10-02T20:13:00.933 回答
0

您应该查看msdn并阅读有关绑定标志的信息。具体来说:

您必须指定 Instance 或 Static 以及 Public 或 NonPublic,否则将不返回任何成员。

于 2012-10-02T20:22:44.330 回答