首页 > 解决方案 > 确定对象是否具有具有特定子值的传递类型的字段

问题描述

我想知道是否可以确定一个对象是否具有特定类型的字段(我相信这可以通过使用 GetField(name) 的反射来完成),然后确定该字段是否具有特定值。

例如,假设我们有以下内容:

public class Foo
{
    public string Value;
}

public class Bar
{
    public string Value;
}

public class Abc
{
    public Foo Foo;
    public Bar Bar;
}

我希望能够做到以下几点:

public static class FieldChecker
{
    public static bool HasDesiredValue(Abc abcObject, Type fieldType, string value)
    {
        FieldInfo info = abcObject.GetType().GetField(fieldType.Name); //See notes below on why this is ok

        if (info != null && info.FieldType == fieldType)
        {
            //Here is my issue. This obviously isn't real code. Can something like this be done?
            if (abcObject.[FieldWithPassedInTypeAndName].Value == value)
            {
                return true;
            }
        }

        return false;
    }
}

像这样使用:

Abc abcObject = new Abc()
{
    Foo = new Foo()
    {
        Value = "SomeValue"
    }
};

bool boolOne = FieldChecker.HasDesiredValue(abcObject, typeof(Foo), "SomeValue"); //true
bool boolTwo = FieldChecker.HasDesiredValue(abcObject, typeof(Foo), "SomeOtherValue"); //false

笔记:

标签: c#reflectionfield

解决方案


我建议使用以下代码:

// Check if the object has said property
public static bool HasProperty(this object obj, string property)
{
    return obj.GetType().GetProperty(property) != null;
}

// Get property value
public static object GetPropertyValue(this object obj, string property)
{
    return obj.GetType().GetProperty(property).GetValue(obj, null);
}

public static bool HasDesiredValue(Abc abcObject, Type fieldType, string value)
{
    if (abcObject.HasProperty(fieldType.Name))
    {
        if (abcObject.GetPropertyValue(fieldType.Name).GetPropertyValue("value").ToString().Equals(value))
        {
            return true;
        }
    }
    return false;
}

当然,您需要进行大量验证并在边缘工作以确保安全,但这就是要点。


推荐阅读