set-variables-from-an-object-using-reflection

133

set-variables-from-an-object-using-reflection -

public void Validate(object o)
{
    Type t = o.GetType();
    foreach (var prop in
        t.GetProperties(BindingFlags.Instance | BindingFlags.Public))
    {
        if (Attribute.IsDefined(prop, typeof(RequiredAttribute)))
        {
            object value = prop.GetValue(o, null);
            if (value == null)
                throw new RequiredFieldException(prop.Name);
        }
    }
}

set-variables-from-an-object-using-reflection -

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

        //Fields durchlaufen
        foreach (var fieldInfo in item.GetType().GetFields())
        {
            object fieldObject = Activator.CreateInstance(fieldInfo.FieldType);

            // Or if it's already instantiated: 
            // object fieldObject = fieldInfo.GetValue(item);

            foreach (var fieldProperty in fieldInfo.FieldType.GetProperties())
            {
                fieldProperty.SetValue(fieldObject, "TestData not work", null); // this doesent work
            }
            fieldInfo.SetValue(item, fieldObject);
        }
        return item;
    }
}

Comments

Submit
0 Comments