如何将单一类型的类属性转换为该类型的列表
给定以下类:
class MyClass {
readonly MyType Object1 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
readonly MyType Object2 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
readonly MyType Object3 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
readonly MyType Object4 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
// etc, there are 100+ in this class, all of the type MyType
}
有没有办法将其变成类型myType
或prop prop1
的列表?
该类仅包含类型myType
的属性。
Given the following class:
class MyClass {
readonly MyType Object1 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
readonly MyType Object2 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
readonly MyType Object3 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
readonly MyType Object4 = new MyType { Prop1="Prop I want", Prop2="Prop I dont want"}
// etc, there are 100+ in this class, all of the type MyType
}
Is there a way I can turn this into a list of either the type MyType
or the prop Prop1
?
The class only contains properties of the type MyType
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为此,我们将使用 reflection 要获取
prop1
myClass
中所有字段的属性中的所有字符串列表。鉴于您有一些
myClass
的实例,因此可以获取带有这样简单单线的字符串列表:如果您突然想在
myType ,您可以简单地更改您在最后一个
select()
中选择的属性。在这里,我们使用反射以获取所有字段(
.getRuntimeFields()
),myClass
,并且由于我们知道所有字段均为typemyType 我们只能将所有字段投放到
myType
,然后只需选择prop1
属性即可。最后,我们只是做tolist()
将其作为列表,您当然可以将其用作iEnumerable< string>
或一个数组,但希望这应该向您显示您如何获得想要作为列表的属性。如果您只想拥有
myType
的列表,那么您可以跳过最后的select()
这样:To do this, we will use Reflection to get a list of all strings in the
Prop1
properties of all fields inMyClass
.Given that you have some instance of
MyClass
, you can get the list of strings with a simple one-liner like this:If you suddenly want to get some other property inside of
MyType
, you can simply change which property you select in the lastSelect()
.Here we use reflection to get all fields (
.GetRunTimeFields()
) inside of the typeMyClass
, and since we know that all fields are of typeMyType
we can just cast all of the fields toMyType
and then simply select theProp1
property. Finally we just doToList()
to have it as a list, you could of course use it as anIEnumerable<string>
or an array, but hopefully this should show you how you get the property you wanted as as list.If you instead just want to have a list of
MyType
, then you could skip the lastSelect()
like this: