如何将类的所有属性存储在对象数组中?
假设我有一个类 myClass ,它有几个属性,例如 property1、property2、perperty3 等。现在,我想用每个属性填充一个数组,以便我可以通过其索引访问每个属性。有没有一种自动的方法可以做到这一点?
以下是来自 SportsStore(Pro ASPN.NET MVC/Steve Sanderson/Apress)的示例,介绍如何收集“程序集”中的所有活动控制器。
var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
foreach(Type t in controllerTypes)
//Do something
我想知道是否有类似上面的东西我可以用来收集(仅)类的属性并将它们存储在数组中,无论每个类型值(int,string或自定义类型)如何
我希望我能够清楚地表达自己。否则我可以修改文本。
谢谢你的帮助。
Let's say I've a class myClass which has few properties, such as property1, property2, perperty3, etc. Now, I'd like to populate an array with each of those properties so that, I can access each of them through its index. Is there an automatic way of doing so?
Here's an example from SportsStore (Pro ASPN.NET MVC/Steve Sanderson/Apress) on how to gather all the active controllers in the the 'Assembly'.
var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
foreach(Type t in controllerTypes)
//Do something
I wonder if there is some thing like the one above I can use to collect (only) properties of a class and store them in a array, no matter each one's type value (int, string, or custom type)
I hope I was able to express myself clearly. Otherwise I can amend the text.
Thanks for helping.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用反射:
和看起来更好的 LINQ 版本:
You could use reflection:
and LINQ version which looks better to the eye:
我从这里得到这个:
I got this from here:
Type.GetProperties() 方法帮助你吗?
would the Type.GetProperties() method help you?