开发者

Returning Anonymous Type

I am using a trick to return Anonymous Type but, i m not sure whether it will work in all scenario. If there is any problem using this trick plz let me know so that i will not use this code in my project

class A
{
    public int ID { get; set; }
    public string Name { get; set; }
}

class B
{
    public int AID { get; set; }
    public string Address { get; set; }
}

private List<object> GetJoin()
{
    var query = from a in objA
                join b in objB
                on a.ID equals b.AID
                select new { a.ID, a.Name, b.Address };
    List<object> lst = new List<object>();
    foreach (var item in query)
    {
        object obj = new { ID = item.ID, Name = item.Name, Address = item.Address };
  开发者_如何学C      lst.Add(obj);
    }
    return lst;
}
T Cast<T>(object obj, T type)
{
    return (T)obj;
}

//call Anonymous Type function
foreach (var o in GetJoin())
{
    var typed = Cast(o, new { ID = 0, Name = "", Address = "" });
    int i = 0;
}


Yes, that's guaranteed to work so long as everything is within the same assembly. If you cross the assembly boundary, it won't work though - anonymous types are internal, and the "identity" is based on:

  • Assembly it's being used in
  • Properties:
    • Name
    • Type
    • Order

Everything has to be just right for the types to be considered the same.

It's not nice though. For one thing, your GetJoin method can be simplified to:

return (from a in objA
        join b in objB
        on a.ID equals b.AID
        select (object) new { a.ID, a.Name, b.Address })
       .ToList();

... and for another, you've lost compile-time type safety and readability.

I think you'd be a lot better off creating a real type to encapsulate this data. Admittedly it would be lovely if we could create a named type which was the equivalent to the anonymous type, just with a name... but that's not available at the moment :(


You cannot return Anonymous Types without using Object type. And using Object type, you lose member access.

You have two options:

  • Create a type. (Recommended)
  • Use dynamic type to access members
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜