c# - 确定对象是否具有具有特定子值的传递类型的字段
问题描述
我想知道是否可以确定一个对象是否具有特定类型的字段(我相信这可以通过使用 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
笔记:
- 字段名称和字段类型将始终相同,这就是我可以使用 GetField(fieldType.Name) 的原因。如果有更好的方法可以做到这一点,我欢迎反馈。
- 我有兴趣检查的东西将始终被调用
Value
,并且始终是传入类型的字段上的一个字段,所以如果有办法获取该字段,那么[whatever].Value
这就是我有兴趣检查的内容,nomatter我传入的字段类型。 - 只会有 1 个具有所需类型的字段(即类中永远不会有 2 个
Foo
字段Abc
,即使我只对名为 的字段感兴趣Foo
) - 在现实世界中,Abc 对象是使用反序列化生成的。我没有在代码中初始化它。
- Abc 类是由工具生成的,因此它不能(不应该)被编辑,所以我不能将它作为 Abc 类中的方法。我也有兴趣检查很多不同的值(在现实世界中,Abc 类有几十个我有兴趣检查的字段)所以我假设一个通用方法是最简单的。
解决方案
我建议使用以下代码:
// 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;
}
当然,您需要进行大量验证并在边缘工作以确保安全,但这就是要点。
推荐阅读
- javascript - 如何在动画后恢复 div 的宽度?
- c++ - 是自动类型检测只看一个语句
- php - Laravel & vuejs cpanel 共享托管应用迁移问题
- javascript - 如何使用 React-Redux 停止在 React 中显示错误消息
- java - Spring JPA MYSQL 日期减一天
- angular - 多个组合框规则集组件
- javascript - 如何在移动 iO 上启用平滑滚动?
- vue.js - Vuejs - 在插槽中使用 HTMLElement 后,对 HTMLElement 的引用变得陈旧
- docker - 您可以在执行 docker-compose pull 时指定要拉取的标签吗?
- python - 在布尔张量掩码中查找峰值点的索引(第一个 True)