Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

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;
    }
}
Comment

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);
        }
    }
}
Comment

PREVIOUS NEXT
Code Example
Csharp :: get appsetting.json config .net 
Csharp :: quick watch in visual studio 
Csharp :: class merging 
Csharp :: nodatime instant to datetime off set c# 
Csharp :: chrome devtools capture all styling an element uses 
Csharp :: detect location from ip address .net core 
Csharp :: tostring vb.net format decimal value with comma 
Csharp :: json.net jobject replace value 
Csharp :: what is the difference between rotation rotation axis and equator 
Csharp :: ${1##*[! ]} 
Csharp :: dateTime to dataRow in c# 
Csharp :: C# USING SHARED CLASS 
Csharp :: c# how to use or operator on integers in while loop 
Csharp :: copy array to array in c# 
Csharp :: duplicate global system runtime versioning targetframeworkattribute 
Csharp :: material Array setter 
Csharp :: Process.Start(osk.exe) 
Csharp :: difference between %e/E, %f/F and %g/G in program C 
Csharp :: DateTime2 error in EF Blazor Web Application 
Csharp :: Appending to an Existing CSV File with csvhelper 
Csharp :: c# ef dynamic ApplyConfiguration 
Csharp :: convert physical path to virtual path in c# 
Csharp :: insert keys automatically dictionary in c# 
Csharp :: 403 forbidden error using Windows Forms 
Csharp :: c# decimal literal 
Csharp :: get all the file from directory except txt in c# 
Csharp :: C# Func Delegate 
Csharp :: trigger enter with nav mesh 
Csharp :: c# call constructor from constructor 
Csharp :: resize image and add watermark c# 
ADD CONTENT
Topic
Content
Source link
Name
8+9 =