开发者

C# object creator

In javascript, I often use something like t开发者_如何学运维his object creator

  var o = new Object(); // generic object
  var props = { color:"red",value:5 }; // hashtable
  for(var key in props) o[key] = props[key];
  alert(o.color); //red

Can it be written as C# method with this declaration?

  static void properties(out Object o, HashTable h) { ...

Is this some design pattern? Am I inventing wheel?


You may want to look at the Expando Object in C# 4. That is about as close as you are going to get to a dynamic object in C# like you can get in JavaScript.

http://msdn.microsoft.com/en-us/magazine/ff796227.aspx

http://www.c-sharpcorner.com/blogs/BlogDetail.aspx?BlogId=2134


        var test = new { name = "Testobj", color = Colors.Aqua };
        MessageBox.Show(test.name);

It's called a anonymous Type, I think this is what you are searching for.


Since c# is statically typed, you cannot achieve this.. closest possible is anonymous methods

Dictionary<string,int> dic=new Dictionary<string,int>();
            dic.Add("red", 5);
            dic.Add("black", 10);
            dic.Add("white", 1);
            object[] obj;
            foreach(var o in dic)
            {
                var sam= new { color = o.Key,value=o.Value };
                Console.WriteLine(sam.color);               

            }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜