PropertyInfo[] properties = entity.GetType().GetProperties()
.Where(p => p.GetMethod.IsVirtual).ToArray();
Hoặc, cho .NET 4 và dưới đây:
PropertyInfo[] properties = entity.GetType().GetProperties()
.Where(p => p.GetGetMethod().IsVirtual).ToArray();
Đó sẽ nhận được một danh sách các công ảo tính chất.
Nó sẽ không hoạt động đối với thuộc tính chỉ ghi. Nếu cần, bạn có thể kiểm tra CanRead
và CanWrite
theo cách thủ công và đọc phương thức thích hợp.
Ví dụ:
PropertyInfo[] properties = entity.GetType().GetProperties()
.Where(p => (p.CanRead ? p.GetMethod : p.SetMethod).IsVirtual).ToArray();
Bạn cũng có thể chỉ cần lấy các accessor đầu tiên:
PropertyInfo[] properties = entity.GetType().GetProperties()
.Where(p => p.GetAccessors()[0].IsVirtual).ToArray();
Nguồn
2012-09-06 18:17:21
Để xử lý một cách an toàn các thuộc tính riêng tư bạn có thể thực hiện: '(p.CanRead? P.GetGetMethod (true): p.GetSetMethod (true)). IsVirtual;' –