简体   繁体   中英

Create an anonymous type dynamically

I am able to creaate a dynamic type at edittime

var orderFields = new
                {
                    legs = new[] {
                        new { 
                             instrumenttype = "Equity Option", 
                             symbol = "SPY   221021C00422000",
                             quantity = "1",
                             action = "Buy to Open"
                        },
                        new {
                             instrumenttype = "Equity Option",
                             symbol = "SPY   221021C00420000",
                             quantity = "1",
                             action = "Sell to Open"
                        },
                    }
                };

However, I don't know how many of these there will be at runtime :

new { 
         instrumenttype = "Equity Option", 
         symbol = "SPY   221021C00422000",
         quantity = "1",
         action = "Buy to Open"
    },

The source of the instances could be a List<DataRow> , or List<Struct>

I am able to do this at edittime ok, but don't know how to fill in the rest at runtime:

var orderFields = new
                {
                    
                };

How do I create an anonymous type at runtime and add these to the legs [] ?

Anonymous types are not anonymous at runtime. The compiler creates types.

There is a way to create new types at runtime, using reflection. Use TypeBuilder.CreateType for that.

Depending on your requirements, there may be other ways to achieve your goal. Look into the dynamic ExpandoObject. This is in essence a dictionary, but combined with the dynamic keyword, it behaves like a dynamic type.

There is humor in programming, I literally laughed out loud when this worked, because I just dreamed this up and was shocked that it compiled at all, AND it actually works! LOL!

public class Leg
{
    public string instrumenttype { get; set; }
    public string symbol { get; set; }
    public string quantity { get; set; }
    public string action { get; set; }
}

var leg1 = new Leg { instrumenttype = "Equity Option", symbol = "SPY   221021C00422000", quantity = "1", action = "Buy to Open" };
var leg2 = new Leg { instrumenttype = "Equity Option", symbol = "SPY   221021C00420000", quantity = "1", action = "Sell to Open" };

var Legs = new Leg[2] { leg1, leg2 };

var orderFields = new
{
    Legs
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM