cod*_*sed 4 .net c# system.reflection
我有一个包含一些ICollection类型属性的对象
所以基本上这个类看起来像这样:
Class Employee {
public ICollection<Address> Addresses {get;set;}
public ICollection<Performance> Performances {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
问题是通过使用反射获取Generic类内部的ICollection类型的属性名称.
我的通用类是
Class CRUD<TEntity> {
public object Get() {
var properties = typeof(TEntity).GetProperties().Where(m=m.GetType() == typeof(ICollection ) ...
}
Run Code Online (Sandbox Code Playgroud)
但它没有用.
我怎样才能在这里获得房产?
GetProperties()返回一个PropertyInfo[].然后你做一个Where使用m.GetType().如果我们假设你错过了一个>,那就是m=>m.GetType(),那么你实际上是在说:
typeof(PropertyInfo) == typeof(ICollection)
Run Code Online (Sandbox Code Playgroud)
(警告:实际上,它可能是RuntimePropertyInfo等等)
你的意思可能是:
typeof(ICollection).IsAssignableFrom(m.PropertyType)
Run Code Online (Sandbox Code Playgroud)
然而!注意ICollection<> ICollection<><> ICollection<Address>等 - 所以它甚至不那么容易.您可能需要:
m.PropertyType.IsGenericType &&
m.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>)
Run Code Online (Sandbox Code Playgroud)
确认; 这工作:
static void Main()
{
Foo<Employee>();
}
static void Foo<TEntity>() {
var properties = typeof(TEntity).GetProperties().Where(m =>
m.PropertyType.IsGenericType &&
m.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>)
).ToArray();
// ^^^ contains Addresses and Performances
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1674 次 |
| 最近记录: |