如何搜索对象是否具有值为 C# 的属性

Mic*_*r3D 5 c# reflection

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

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

    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;
    }

}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ble 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在我看来,你应该接受propertyValue作为一个object与对象同样比较,但会表现出比原来的样品不同的行为。