Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Challenge: Reflection | Generics & Reflection
C# Desktop Development with .NET MAUI

Challenge: Reflection

Scorri per mostrare il menu

In summary, Your task is to fill in the blanks where necessary to implement reflection.

The task is explained in the following video:

Hint
expand arrow
  1. The GetProperties() method of the Typecode> class returns an array of all the public properties in a Type.
  2. The GetProperty(propertyName)code> method of the Typecode> class returns a reference to a single property which matches the propertyName.
  3. The SetValue(object, value) method of the PropertyInfo class sets the property value of the object to value.
Solution
expand arrow
using System.Reflection;
using System.Security.AccessControl;

namespace ObjectManagerTask
{
    class Product
    {
        private static int Products = 0;

        private int ID { get; }
        public string Name { get; set; }
        public float Price { get; set; }
        public string Description { get; set; }

        public int Quantity { get; set; }

        public Product()
        {
            this.Name = "";
            this.Price = 0.0f;
            this.ID = Products++;
            this.Description = "";
        }
    }

    public partial class MainPage : ContentPage
    {
        List<Product> products = new List<Product>();
        public MainPage()
        {
            InitializeComponent();

            // Store the type of product class
            Type productType = typeof(Product);

            // Get all the properties of the Product class
            PropertyInfo[] properties = productType.GetProperties();

            // Loop through all the properties
            foreach (PropertyInfo property in properties)
            {
                Entry entryBox = new Entry();
                entryBox.Placeholder = property.Name;
                fields.Children.Add(entryBox);
            }

            createBtn.Clicked += CreateProduct;
        }

        void CreateProduct(object? sender, EventArgs e)
        {
            try
            {
                Product product = new Product();

                // Store the type of product class
                Type productType = product.GetType();

                foreach (Entry entryBox in fields.Children)
                {
                    // Get the property reference from the Product class, which has the same name as 'entryBox.Placeholder'.
                    // The exclamation mark ensures the compiler that the retrieved reference is not going to be null. 
                    // It is to suppress the warning.
                    PropertyInfo property = productType.GetProperty(entryBox.Placeholder)!;

                    object value = Convert.ChangeType(entryBox.Text, property.PropertyType);
                    property.SetValue(product, value);
                }

                products.Add(product);
            }
            catch
            {
                infoLabel.Text = $"ERROR: Invalid value in one of the fields.";
                return;
            }

            infoLabel.Text = $"Product {products.Count} created successfully.";

            ClearEntryBoxes();
            UpdateProductsList();
        }

        void UpdateProductsList()
        {
            productsList.Children.Clear();

            // Store the type of Product class
            Type productType = typeof(Product);

            foreach (Product product in products)
            {
                Label dataLabel = new Label();

                // Retrieve all the properties of productType
                PropertyInfo[] properties = productType.GetProperties();

                // Loop through all the properties
                foreach (PropertyInfo property in properties)
                {
                    // Get the value of 'property' from the 'product' object.
                    // The exclamation mark is to suppress the compiler warning since we know that the property exists,
                    // and it cannot return null.
                    object value = property.GetValue(product)!;

                    dataLabel.Text += $"{property.Name}: {value.ToString()}\t";
                }

                productsList.Children.Add(dataLabel);
            }
        }

        void ClearEntryBoxes()
        {
            foreach (Entry entryBox in fields.Children)
            {
                entryBox.Text = "";
            }
        }
    }
}
Video
expand arrow
Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 8

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 4. Capitolo 8
some-alt