gpt4 book ai didi

c# - 通过反射查找给定/动态类型的 ObservableCollection

转载 作者:太空宇宙 更新时间:2023-11-03 10:49:58 25 4
gpt4 key购买 nike

我有一个包含多个不同类型的 ObservableCollection 的类。现在,我想通过反射找到给定类型的正确集合,因为我不想构建一个每次添加另一个集合时都必须更新的 if-monster。

这个方法是第一步:

public ObservableCollection<T> GetObservableCollectionForType<T>()
{

foreach (PropertyInfo info in this.GetType().GetProperties())
{

if (info.GetGetMethod() != null && info.PropertyType == typeof(ObservableCollection<T>))
return (ObservableCollection<T>)this.GetType().GetProperty(info.Name).GetValue(this, null);

}

return null;

}

现在,我需要第二种方法,它接受一个具体对象作为参数并找到正确的集合。有点像这样:

public ObservableCollection<T> GetObservableCollectionFor(object sObject)
{

Type wantedType = sObject.GetType();

foreach (PropertyInfo info in this.GetType().GetProperties())
{

if (info.GetGetMethod() != null && info.PropertyType == ObservableCollection<wantedType>)
return this.GetType().GetProperty(info.Name).GetValue(this, null);

}

return null;

}

有什么想法可以实现吗?

更新:

可行的解决方案:

public object GetObservableCollectionFor(object sObject)
{

Type wantedType = sObject.GetType();

foreach (PropertyInfo info in this.GetType().GetProperties())
{

if (info.GetGetMethod() != null && info.PropertyType == typeof(ObservableCollection<>).MakeGenericType(new[]{wantedType}))
return this.GetType().GetProperty(info.Name).GetValue(this, null);

}

return null;

}

这将返回正确的集合作为对象。我仍然不知道如何转换为正确的泛型类型,但转换为 IList 足以添加和删除。

最佳答案

比较属性的类型时,您似乎需要在 ObservableCollection 类型上添加对 MakeGenericType() 的调用。还没有测试过这个,但也许是这样的......

public ObservableCollection<T> GetObservableCollectionFor(object sObject)
{

Type wantedType = sObject.GetType();

foreach (PropertyInfo info in this.GetType().GetProperties())
{

if (info.GetGetMethod() != null && info.PropertyType == typeof(ObservableCollection<>).MakeGenericType(new[]{Type.GetType(wantedType)})

return (ObservableCollection<T>)this.GetType().GetProperty(info.Name).GetValue(this, null);

}

return null;

}

编辑为了避免对值类型进行开销装箱,可以通过将参数类型从对象更改为类型 T 来改进上述方法定义

public ObservableCollection<T> GetObservableCollectionFor(T sObject)

关于c# - 通过反射查找给定/动态类型的 ObservableCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21782154/

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