开发者

dynamically create a class in c#.net

开发者 https://www.devze.com 2023-03-22 03:55 出处:网络
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 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.


Try look here:

Dynamic in C# 4.0: Introducing the ExpandoObject


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´s a handy tutorial:

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

0

精彩评论

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