jeudi 27 avril 2017

C# set variables from an object using Reflection doesn't work

I want to set variables from an object using Reflection.

For simple object this works. (Propertys)

But objects with class variables (Fields) doesn’t work. Here I get always an Exeption with "The object does not agree with the target type."

Has anyone here an idea how it could go?

namespace Question
{
    class Program
    {
        static void Main(string[] args)
        {
            var genericDataSet = new GenericDataSet<DataObjekt>();
            var returnObjekt = genericDataSet.KeepElementsData();
        }
    }

    public class DataObjekt
    {
        public string Name { get; set; }
        public ObjektData ModelTyp;
        public DataObjekt() { ModelTyp = new ObjektData(); }
    }

    public class ObjektData
    {
        public string Typ { get; set; }
        public string Data { get; set; }
    }

    public class GenericDataSet<T> where T : class, new()
    {
        public T KeepElementsData()
        {
            var item = new T();
            //Propertys durchlaufen
            foreach (var Property in item.GetType().GetProperties())
            {
                item.GetType().GetProperty(Property.Name).SetValue(item, "TestData");  //this works
            }

            //Fields durchlaufen
            foreach (var Field in item.GetType().GetFields())
            {
                foreach (var FieldProperty in item.GetType().GetField(Field.Name).FieldType.GetProperties())
                {
                    var data = item.GetType().GetField(Field.Name).FieldType.GetProperty(FieldProperty.Name);
                    data.SetValue(item, "TestData not work", null); // this doesent work
                }
            }
            return item;
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire