C# 利用反射去除对象中的NotMapped或其他属性

  • Post author:
  • Post category:其他


引用 using Newtonsoft.Json.Linq;

及命名空间 System.Reflection;

传统实现,去除实例中的属性

public static T RemoveAttribute<T>(T entity){
    JObject jObject = JObject.FromObject(entity);
    jObject.Remove("AttributeName1");
    jObject.Remove("AttributeName2");
    entity = JsonConvert.DeserializeObject<T>(jObject.ToJson());
}

利用反射查出类中所有的NotMapped注解属性,并remove生成新的类的对象实例

public static T RemoveAttribute<T>(T entity){
	JObject jObject = JObject.FromObject(entity); //将对象转为jobject对象进行操作
	
	Type type = typeof(T); //获取实例具体引用的数据类型
	//PropertyInfo[] properties = type.GetProperties();
	PropertyInfo[] peroperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); //获取所有public的属性
	foreach (PropertyInfo property in peroperties)
	{
		 //循环是否带有NotMapped注解
	     foreach (var NotMapped in property.CustomAttributes)
	     {
	         if (NotMapped.AttributeType.Name == typeof(NotMappedAttribute).Name)
	         {
	             jObject.Remove(property.Name); //查找出所有包含NotMapped注解的属性,并剔除
	             break;
	         }
	     }
	}
	entity = JsonConvert.DeserializeObject<T>(jObject.ToJson());
	return entity;
}



版权声明:本文为weixin_38161834原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。