Creating a dynamic anonymous types variables

家住魔仙堡 提交于 2019-12-06 08:15:32

问题


Can I create an anonymous type variable and later on add more Properties?

E.g. var x = new { Name = "Ahmed" }; and want to add Age to it? how can I do this?

Another question: i saw on some blogs a type AnonymousType what is the name space for this class? here is am example http://www.codeproject.com/KB/cs/AnonymousTypesInCSharp.aspx


回答1:


First question - you can't.

Second question - AnonymousType is the type the author of that article created. You have to download the source for his project to use that type.




回答2:


No, you cant.

2nd question: No such thing, it might refer to compiler generated class which you have no access to.




回答3:


No, and It would not be efficient for Your application. Are You convinced that You don't want to introduce some kind of class?

using System;
class Generic{

   public void doSomething(){}

   private string name;
   private string _othreFeature;

}

You could extend it with new features, whenever You want.




回答4:


This is a perfectly logical question... I work with Java and C# both and this is a big pet peeve of mine... Matter of fact almost every language out there has some sort of Anonymous type lol... PHP, JavaScript, C#, vb (all), and the list goes on..

It's a very useful feature to have when you're basically throwing data into an object and you don't need a class for it created.

Matter of fact this is exactly what LINQ utilizes..

var someObject (can be interable/Enumerable) = 
    from p in products
    where p.id == 123
    select new { productid };

blah blah you get the idea.. It's very useful... :-)

Cheers!



来源:https://stackoverflow.com/questions/1519851/creating-a-dynamic-anonymous-types-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!