开发者

Generics and anonymous type

开发者 https://www.devze.com 2022-12-25 03:30 出处:网络
I understood,normally generics is for compile time safe and allow us to keep strongly typed collection.Then how do generic allow us to store anonymous types like

I understood,normally generics is for compile time safe and allow us to keep strongly typed collection.Then how do generic allow us to store anonymous types like

List<object> TestList = new List<object>();
TestList.Add(new { id = 7, Na开发者_JAVA百科me = "JonSkeet" });
TestList.Add(new { id = 11, Name = "Marc Gravell" });
TestList.Add(new { id = 31, Name = "Jason" });


This works because object is the root type of all instances in .Net. Hence anything expression can be used for a location expecting an object because they all meet the basic contract of System.object.

For example the following is completely legal.

List<object> TestList = new List<object>();
TestList.Add(new { id = 7, Name = "JonSkeet" });
TestList.Add("Foo");
TestList.Add(42);


Because everything is (or can be boxed into) an object, and that's a List of objects.


Others already explained why your code works - your example is strongly typed, because everything is an object, but that means that it's not very useful. You cannot take elements from the list and access for example their Name property, because they are just object, so this cannot work in general.

However, it is possible to create a strongly typed List of anonymous types - it just needs to be done using a small utility method like this:

static List<T> CreateList<T>(params T[] items) {
  return items.ToList();
}

The problem is that you can't call a constructor without providing the name of the type. When calling a method, C# can infer the type parameter, so you can write this:

var testList = CreateList(
  new { id = 7, Name = "JonSkeet" },
  new { id = 11, Name = "Marc Gravell" });
testList.Add(new { id = 31, Name = "Jason" });

This is perfectly type-safe and you can for example write testList[0].Name to get the name of the first person. If you try writing something like testList.Add(42), you'll get a compile-time error, because the list is strongly typed to contain only anonymous types with id and Name properties.

0

精彩评论

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