jeudi 11 juin 2020

C# Iterate through Class Function and Apply function Using Reflection [duplicate]

How do I iterate through all members of a class and multiply its value? Want to locate all members which are int and multiply by 2, using Reflection. Seem to be stuck on line below with error.

class Program
{
    static void Main(string[] args)
    {
        var test = new TestClass();
        test.ProductName = "book";
        test.AmountSold = 5;

        PropertyInfo[] properties = typeof(TestClass).GetProperties();
        foreach (PropertyInfo property in properties)
        {
            if (property.PropertyType == typeof(int))
            {
                property.SetValue(test, property.GetValue * 2);  // stuck in this line
            }
        }
    }
}

public class TestClass
{
    public string ProductName { get; set; }
    public int AmountSold { get; set; }
}

Error: CS0019 Operator '*' cannot be applied to operands of type 'method group' and 'int





Aucun commentaire:

Enregistrer un commentaire