Domanda

ho questo

dynamic d = new ExpandoObject();
d.Name = attribute.QualifiedName.Name;

Quindi, so che D avrà un nome di proprietà. Ora, se non conosco il nome della proprietà al momento della compilazione, come posso aggiungere quella proprietà alla dinamica. ho trovato questo Quindi domande

Quindi, c'è questo complicato concetto di raccoglitori di chiamate ecc. Che è difficile da ottenere in primo luogo. Qualsiasi modo più semplice per farlo?

È stato utile?

Soluzione

dynamic d = new ExpandoObject();
((IDictionary<string,object>)d)["test"] = 1;
//now you have d.test = 1

Altri suggerimenti

Ecco un modo più pulito

var myObject = new ExpandoObject() as IDictionary<string, Object>; myObject.Add("Country", "Ireland");

Puoi anche fare così:-

Dictionary<string,object> coll = new Dictionary<string,object>();
    coll.Add("Prop1","hello");
    coll.Add("Prop2",1);
    System.Dynamic.ExpandoObject obj = dic.Expando();

//You can have this ext method to better help

public static ExpandoObject Expando(this IEnumerable<KeyValuePair<string, object>> 
dictionary)
        {
            var expando = new ExpandoObject();
            var expandoDic = (IDictionary<string, object>)expando;
            foreach (var item in dictionary)
            {
                expandoDic.Add(item);
            }
            return expando;
        }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top