如何通过反射检查属性是否是虚拟的? [英] How to check if a property is virtual with reflection?
本文介绍了如何通过反射检查属性是否是虚拟的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个对象,我如何判断该对象是否具有虚拟属性?
Given an object, how can I tell if that object has virtual properties?
var entity = repository.GetByID(entityId);
我试着往里看:
PropertyInfo[] properties = entity.GetType().GetProperties();
但无法辨别是否有任何属性表示虚拟.
But couldn't discern if any of the properties would indicate virtual.
推荐答案
PropertyInfo[] properties = entity.GetType().GetProperties()
.Where(p => p.GetMethod.IsVirtual).ToArray();
或者,对于 .NET 4 及以下版本:
Or, for .NET 4 and below:
PropertyInfo[] properties = entity.GetType().GetProperties()
.Where(p => p.GetGetMethod().IsVirtual).ToArray();
这将得到一个公共虚拟财产的列表.
That will get a list of public virtual properties.
它不适用于只写属性.如果需要,您可以手动检查CanRead
和CanWrite
,并读取相应的方法.
It won't work for write-only properties. If it needs to, you can check CanRead
and CanWrite
manually, and read the appropriate method.
例如:
PropertyInfo[] properties = entity.GetType().GetProperties()
.Where(p => (p.CanRead ? p.GetMethod : p.SetMethod).IsVirtual).ToArray();
您也可以只获取第一个访问器:
You could also just grab the first accessor:
PropertyInfo[] properties = entity.GetType().GetProperties()
.Where(p => p.GetAccessors()[0].IsVirtual).ToArray();
这篇关于如何通过反射检查属性是否是虚拟的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文