我收到许多不同的消息,我将它们反序列化为非常不同的对象
这些对象中的大多数都具有不可为 null 的字段,但在所有消息类型中(从 GraphQL、Azure 服务和存储总线,到 CosmosSB 以及可能还有更多我忘记的对象),其中一些对象很乐意反序列化为对象无论如何都有空字段。
因此,我非常可以使用一个可以让我做的组件
T objectFromMessage = GetObject(message);
FieldAsserter.AssertAllFieldsSet<T>(objectFromMessage); //Throws if any non-nullable fields are null
您知道是否已经存在这样的字段验证方法(默认情况下或 Nuget 中的某个位置)吗?或者,如果我必须自己写,你能给我任何线索吗?从哪里开始寻找?
What did you try and what were you expecting?
在这一点上,什么都没有 - 在思考“也许 SO 有答案”之前,我对 NuGet 进行了粗略搜索,并对反射进行了一些思考。
已经有几个类似的问题了,但它们似乎适用于单个对象 - 答案的类型是“为你的类编写一个扩展方法来执行它”,但我想要一个通用方法适用于任何事情 - 我的消息类型太多。
最佳答案
您正在寻找像下面这样简单的东西吗?您还可以添加自定义或默认属性来指示在此检查中忽略某个属性。
public static bool AreAllPropertiesNotNull<T>(this T obj) where T : class
{
PropertyInfo[] properties = typeof(T).GetProperties();
foreach (PropertyInfo property in properties)
{
if (property.GetCustomAttribute<IgnoreAttribute>() != null)
{
continue; // Skip properties with Ignore attribute
}
dynamic propertyValue = property.GetValue(obj);
if (propertyValue == null)
{
return false;
}
}
return true;
}
使用扩展方法。
T objectFromMessage = GetObject(message);
Assert.True(objectFromMessage.AreAllPropertiesNotNull());
关于c# - 是否有一种通用方法可以递归地检查反序列化对象的空字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75985831/