简体   繁体   中英

Instantiate all properties and sub properties in an object (C#.net)

I have an object (x) with about 100 properties. Most of these properties are reference types that will need to be instantiated before I can do anything with x. Also, many of the properties on x will have properties that will also need to be instantiated.

I've thought to use reflection and recursion, but I'm still a little bit stuck on how the implementation would work. My current implementation involves looping through the PropertyInfo Array, and using SetValue from Activator.CreateInstance. As I drill down through x, I'm getting a lot of exceptions:

  • No parameterless constructor defined for this object.
  • Cannot create an abstract class.
  • Property set method not found.

Should I just account for these cases, or is there a better way to be doing this? Ultimately, it's not assigning values to everything I need still. Thanks for your help.

可能这太过分了,但是有这么大的对象似乎是指向类的层次结构(您提到过抽象类),所以我将使用正确配置的DI容器(例如Unity)为我完成工作。

You are looking for Dependency Injection, .NET included Managed Extensibility Framework, which supports creating objects with properties and with proper lifecycle control.

However, it will still give exceptions when it cannot instantiate types, but instead of creating all types, MEF provides attributes and other ways to control what types should be instantiated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM