提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
在上一篇文章中写了使用Newtonsoft.Json格式化输出,这次让我们来用反射来实现。
一、反射是什么?
反射指程序可以访问、检测和修改它本身状态或行为的一种能力。
程序集包含模块,而模块包含类型,类型又包含成员。反射则提供了封装程序集、模块和类型的对象。
您可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型。然后,可以调用类型的方法或访问其字段和属性。
优缺点
优点:
1、反射提高了程序的灵活性和扩展性。
2、降低耦合性,提高自适应能力。
3、它允许程序创建和控制任何类的对象,无需提前硬编码目标类。
缺点:
1、性能问题:使用反射基本上是一种解释操作,用于字段和方法接入时要远慢于直接代码。因此反射机制主要应用在对灵活性和拓展性要求很高的系统框架上,普通程序不建议使用。
2、使用反射会模糊程序内部逻辑;程序员希望在源代码中看到程序的逻辑,反射却绕过了源代码的技术,因而会带来维护的问题,反射代码比相应的直接代码更复杂。
二、源代码
代码如下(示例):
void Main()
{
var obj = new SampleClass
{
Name = "-",
Description = "",
NestedObjects = new List<SampleClass>
{
new SampleClass { Name = "-", Description = "" },
new SampleClass { Name = "Valid Name", Description = "Valid Description" }
}
};
EmptyStringAndHyphenToNullConverter.Convert(obj);
JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented).Dump();
}
public class SampleClass
{
public string Name { get; set; }
public string Description { get; set; }
public List<SampleClass> NestedObjects { get; set; }
}
public static class EmptyStringAndHyphenToNullConverter
{
public static void Convert(object obj)
{
if (obj == null) return;
Type type = obj.GetType();
// If obj is a collection
if (typeof(IEnumerable).IsAssignableFrom(type) && type != typeof(string))
{
IList list = obj as IList;
if (list != null)
{
for (int i = list.Count - 1; i >= 0; i--)
{
var item = list[i];
Convert(item);
if (AllPropertiesNull(item))
{
list.RemoveAt(i);
}
}
}
else
{
foreach (var item in (IEnumerable)obj)
{
Convert(item);
}
}
}
else
{
// Traverse all properties
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
// Skip if the property is not readable or writable
if (!property.CanRead || !property.CanWrite) continue;
var value = property.GetValue(obj);
if (value == null) continue;
if (property.PropertyType == typeof(string))
{
string stringValue = value as string;
if (stringValue == "-" || string.IsNullOrEmpty(stringValue))
{
property.SetValue(obj, null);
}
}
else if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType))
{
if (property.PropertyType != typeof(string))
{
Convert(value);
if (property.GetValue(obj) is IList list)
{
for (int i = list.Count - 1; i >= 0; i--)
{
var item = list[i];
if (AllPropertiesNull(item))
{
list.RemoveAt(i);
}
}
}
}
}
else if (!property.PropertyType.IsPrimitive && property.PropertyType != typeof(decimal))
{
Convert(value);
}
}
}
}
private static bool AllPropertiesNull(object obj)
{
if (obj == null) return true;
Type type = obj.GetType();
if (typeof(IEnumerable).IsAssignableFrom(type) && type != typeof(string))
{
return obj is ICollection collection && collection.Count == 0;
}
return type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.All(p => p.GetValue(obj) == null);
}
}
2.说明
typeof(IEnumerable).IsAssignableFrom(type)
typeof(IEnumerable).IsAssignableFrom(type)检查type是否实现了IEnumerable接口或者是否是IEnumerable的派生类型。
type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
通过使用BindingFlags.Public | BindingFlags.Instance,你告诉GetProperties方法只返回那些公共且非静态的属性。
!property.PropertyType.IsPrimitive
property.PropertyType获取当前属性的类型的Type对象。
IsPrimitive是Type类的一个属性,用于检查当前类型是否是原始类型。原始类型包括:bool、byte、sbyte、char、short、ushort、int、uint、long、ulong、float、double。
!是逻辑非运算符,表示取反。因此,!property.PropertyType.IsPrimitive检查当前属性的类型是否不是原始类型。
for (int i = list.Count - 1; i >= 0; i--)
采用倒序遍历集合。这种倒序遍历有助于在删除元素时避免索引问题(因为删除元素会导致后续元素的索引发生变化,如果正序遍历的话会有问题)。
总结
希望能够对大家有所帮助。
511

被折叠的 条评论
为什么被折叠?



