简体   繁体   中英

dynamically create a class in c#.net

I want to dynamically create a class in c#.net.

I tried using anonymous methods since the number of member variables is given dynamically, i tried like this,

string element = "element";
string str = String.Empty;
for (int i = 0; i < elementsCount; i++)
{
    str = String.Concat(str, element + i, "=String.Empty", ",");
    if (i == elementsCount - 1)
        str = String.Concat(str, element + i, "=String.Empty");
}
string s = "new{" + str + "}";
var a=s;

and

i want to assign the class 'a' like ObservableCollection but i could not do this.

Is there any way to do these two?? but this is not the right way i guess;

It isn't a very helpful idea to create a class on the fly, since none of your other code will be able to talk to it at compile time. What is the objective here? Options:

  • use a Dictionary<string,object> to return data keyed by name
  • in 4.0, use ExpandoObject , which has both dictionary and dynamic APIs
  • if this is for databinding, implement ICustomTypeDescriptor and provide properties at runtime

For example:

    string element = "element";
    string str = String.Empty;
    int elementsCount = 20;
    IDictionary<string,object> obj = new ExpandoObject();
    for (int i = 0; i < elementsCount; i++)
    {
        obj[element + i] = "value " + i;
    }
    dynamic viaDynamic = obj;
    string val0 = viaDynamic.element0; // = "value 0"

but importantly, this still has the IDictionary<string,object> API for static use.

Do you want to crate classes (types) or instances of existing types?

For the latter look at System.Reflection and the activator class

if you're using .net 4 you can use the DLR from c#

You would have to use Reflection for that, and here´sa handy tutorial:

http://www.csharp-examples.net/reflection-examples/

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