“Set-Variables-From-an-Object-Use-Reflection” Code-Antworten

Set-Variables-From-an-Object-Use-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);
        }
    }
}
DreamCoder

Set-Variables-From-an-Object-Use-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;
    }
}
DreamCoder

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen