lundi 15 janvier 2018

How to insert values into the object from the dictionary? (C#, Expression)

I have a function that uses reflection:

    internal static void SetPropertiesFromDictionary(object entity, Dictionary<string, object> values)
    {
        var typeOfEntity = entity.GetType();

        var entityProperties = typeOfEntity
            .GetProperties(BindingFlags.Instance |                                        
                           BindingFlags.Public | 
                           BindingFlags.DeclaredOnly);

        foreach (var pi in entityProperties)
        {
            values.TryGetValue(pi.Name, out var value);
            if (value != null)
            {
                pi.SetValue(entity,value);
            }
        }
    }

How do I create an expression for setting properties so that I can use reflection only once?





Aucun commentaire:

Enregistrer un commentaire