c# – 通过反射获取所有ICollection属性
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 通过反射获取所有ICollection属性,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2178字,纯文字阅读大概需要4分钟。
内容图文
![c# – 通过反射获取所有ICollection属性](/upload/InfoBanner/zyjiaocheng/794/ee734153c3d44a79b7942b293b4b2c92.jpg)
我正在尝试获取所有ICollection< T>来自未知类型的属性.此外,类型T(集合的内容)在编译时是未知的.首先我尝试过这种方法:
foreach (var property in entity.GetType().GetProperties())
{
if (typeof(ICollection).IsAssignableFrom(property.PropertyType) || typeof(ICollection<>).IsAssignableFrom(property.PropertyType))
{
// do something
}
}
但它不起作用(即使对于ICollection属性也要评估为false).
我得到它像这样工作:
foreach (var property in entity.GetType().GetProperties())
{
var getMethod = property.GetGetMethod();
var test = getMethod.Invoke(entity, null);
if (test is ICollection)
{
// do something
}
}
但我不想执行所有的getter.为什么第一段代码不起作用?如何在不执行所有getter的情况下找到ICollection属性?
解决方法:
事实证明,使用IsAssignableFrom检查您无法找到该接口是否是另一个接口的衍生物:
Console.WriteLine(typeof(ICollection<>).IsAssignableFrom(typeof(ICollection<Int32>)));
Console.WriteLine(typeof(ICollection<Int32>).IsAssignableFrom(typeof(ICollection<>)));
都会写错;
在here的帮助下,这是我能得到的最佳解决方案:
static IEnumerable<PropertyInfo> GetICollectionOrICollectionOfTProperties(this Type type)
{
// Get properties with PropertyType declared as interface
var interfaceProps =
from prop in type.GetProperties()
from interfaceType in prop.PropertyType.GetInterfaces()
where interfaceType.IsGenericType
let baseInterface = interfaceType.GetGenericTypeDefinition()
where (baseInterface == typeof(ICollection<>)) || (baseInterface == typeof(ICollection))
select prop;
// Get properties with PropertyType declared(probably) as solid types.
var nonInterfaceProps =
from prop in type.GetProperties()
where typeof(ICollection).IsAssignableFrom(prop.PropertyType) || typeof(ICollection<>).IsAssignableFrom(prop.PropertyType)
select prop;
// Combine both queries into one resulting
return interfaceProps.Union(nonInterfaceProps);
}
这个解决方案可能会产生一些重复(这几乎不可能,但一定要使用Distinct),它看起来不太好.
但它在具有接口返回类型和具体返回类型的属性的类上运行良好:
class Collections
{
public List<Int32> ListTProp
{
get;
set;
}
public IDictionary<Int32, String> IDictionaryProp
{
get;
set;
}
public ICollection ICollectionProp
{
get;
set;
}
public ICollection<DateTime> IDateTimeCollectionProp
{
get;
set;
}
}
内容总结
以上是互联网集市为您收集整理的c# – 通过反射获取所有ICollection属性全部内容,希望文章能够帮你解决c# – 通过反射获取所有ICollection属性所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。