Working with C# Anonymous Types

前端 未结 8 1532
感动是毒
感动是毒 2020-11-29 12:56

I am calling a method that returns a List variable that contains a c# Anonymous Type objects. For example:

List list = new List()         


        
      
      
      
8条回答
  •  臣服心动
    2020-11-29 13:45

    If you have a method like this:

      List GetContactInfo() {
        List list = new List();
        foreach ( Contact c in allContacts ) { 
            list.Add( new { 
                ContactID = c.ContactID, 
                FullName = c.FullName 
            }); 
        } 
        return list;
      }
    
    
    

    You shouldn't really do this, but there's a very ugly and not future-proof technique that you can use:

      static T CastByExample(object target, T example) {
        return (T)target;
      } 
    
      // .....
    
      var example = new { ContactID = 0, FullName = "" };
      foreach (var o in GetContactInfo()) {
        var c = CastByExample(o, example);
        Console.WriteLine(c.ContactID);
      }
    

    It relies on the fact (which can change!) that the compiler reuses anonymous types for types that have the same "shape" (properties names and types). Since your "example" matches the "shape" of the type in the method, the same type is reused.

    Dynamic variables in C# 4 are the best way to solve this though.

    提交回复
    热议问题