开发者

C# How to create objects without class definitions?

开发者 https://www.devze.com 2022-12-30 02:11 出处:网络
Is it possible to create objects at designtime without having to have hard coded class definitions, then populate properties with primitives or even strongly typed data types?

Is it possible to create objects at designtime without having to have hard coded class definitions, then populate properties with primitives or even strongly typed data types?

This might sound confusing, so I will attempt to give you a use case scenario.

Use case:

You have an XML config file that could hold configuration values for connecting to various systems in 开发者_开发百科an SOA application. In C# the XML file is read, but for each system the configuration properties are different (e.g: SQL might have a connection string, while SharePoint might need a username + password + domain + url, while yet an smtp server would need username + password + port + url)

So instead of creating static classes as follows

public class SharePointConfiguration or public class SQLConfiguration, then have each class with custom properties (this is cumbersome)

or

using a 1990's method, an ArrayList or some named collection

Is there not a more preferred way to achieve this? Taking advantage of new language features, that can still offer design time intellisense, which would make the code easier to maintain and less prone to error.

I guess I am looking for some kind of multipurpose .net 4 property holder. Thanks


Use this sample implementation of a PropertyBag.
If property doesn't exist, create it on the fly...

http://www.codeproject.com/KB/recipes/propertybag.aspx


If you want emit code at runtime?

Checkout the Reflection.Emit namespace
OR better
RunSharp - nicer API


What you want is XML, based on a schema. This will give you IntelliSense, including code snippets, at the same time as providing flexibility.


Based on your question (and assuming I'm reading it right), that would be impossible. The closest you could get would be to use the 'dynamic' type and assign your values to properties at runtime on it - the problem being, that dynamic has no Intellisense support, and even with some other kind of solution, the Intellisense would not be available because the properties would only be attached at runtime.

Am I confused on what you are asking?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号