gpt4 book ai didi

c# - 如何获取和使用未知类

转载 作者:行者123 更新时间:2023-11-30 23:18:31 25 4
gpt4 key购买 nike

我想收到ObservableCollection<T>其中 T是未知的。 (我正在做图书馆,所以我不知道分配了什么类(class))

这样的漏洞故事。

1) 我提供一个名为 Prop 的属性和编码器分配 ObservableCollection<T>Prop喜欢关注

Prop = ObservableCollection<T>;  // where T is class which coder defined

2) 然后我收到 Prop并使用反射的方法获取信息(例如 GetProperties、GetType、FullName 等......)

这里不知道属性怎么设计Prop

我把它设计成

ObservableCollection<object> prop;

public ObservableCollection<object> Prop
{
set
{
prop = value;
// here, I'll make process like
// value.GetType().GetProperties() etc.
}
get
{
return prop;
}
}

但是如你所知,如果我分配 ObservableCollection<TestClass> test = new ObservableCollection<TestClass>();Prop ,发生错误

Cannot implicitly convert type 'System.Colletions.ObjectModel.ObservableCollection<TestClass>' to 'System.Collections.ObjectModel.ObservableCollection<object>'

如果你告诉我怎么做,那将是我的荣幸

最佳答案

看来您需要一个具有通用定义的类:

class TestGeneric<T>
{
private ObservableCollection<T> _prop;

public ObservableCollection<T> Prop
{
get
{
return _prop;
}
set
{
_prop = value;
// here, I'll make process like
// value.GetType().GetProperties() etc.
}
}
}

class TestClass
{ }

以便您可以使用通用属性:

        var generic = new TestGeneric<TestClass>();
generic.Prop = new ObservableCollection<TestClass>();

关于c# - 如何获取和使用未知类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40859362/

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