gpt4 book ai didi

c# - 有没有一种通用的方法来检测属性的类型是否为可枚举类型?

转载 作者:IT王子 更新时间:2023-10-29 04:37:06 25 4
gpt4 key购买 nike

鉴于此:

class InvoiceHeader {
public int InvoiceHeaderId { get; set; }
IList<InvoiceDetail> LineItems { get; set; }
}

我目前正在使用这段代码来检测一个类是否具有集合属性:

void DetectCollection(object modelSource)
{
Type modelSourceType = modelSource.GetType();
foreach (PropertyInfo p in modelSourceType.GetProperties())
{
if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(IList<>))
{
System.Windows.Forms.MessageBox.Show(p.Name);
}
}
}

是否有通用的方法来检测 LineItems 是否为可枚举类型?有些会使用其他可枚举类型(例如 ICollection),而不是 IList。

最佳答案

您的代码实际上并不检查属性是否为 Enumerable 类型,而是检查它们是否为通用 IList。试试这个:

if(typeof(IEnumerable).IsAssignableFrom(p.PropertyType))
{
System.Windows.Forms.MessageBox.Show(p.Name);
}

或者这个

if (p.PropertyType.GetInterfaces().Contains(typeof(IEnumerable)))
{
System.Windows.Forms.MessageBox.Show(p.Name);
}

关于c# - 有没有一种通用的方法来检测属性的类型是否为可枚举类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6483096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com