Member 14876288 Ответов: 1

У меня есть ошибка, которую нужно устранить


Привет,

У меня есть проблема, которую нужно решить.

Вот весь код для программы, которую я сделал, перечисленный ниже:

Файл MainPage.язык XAML:

<Page
    x:Class="Arsalan_Salam_991571527_A2.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Arsalan_Salam_991571527_A2"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid RenderTransformOrigin="0.497,0.522">
        <TextBlock HorizontalAlignment="Left" Margin="572,10,0,0" Text="DriveWell Inc." TextAlignment="Center" FontSize="50" VerticalAlignment="Top" Width="374" Height="72"/>
        <TextBlock HorizontalAlignment="Left" Margin="87,88,0,0" Text="Vin Number" TextAlignment="Center" FontSize="30" VerticalAlignment="Top" Width="192" Height="67" RenderTransformOrigin="0.457,-0.751"/>
        <TextBlock HorizontalAlignment="Left" Margin="67,185,0,0" Text="Car Make" TextAlignment="Center" FontSize="30" VerticalAlignment="Top" Width="194" Height="63"/>
        <TextBlock HorizontalAlignment="Left" Margin="87,282,0,0" Text="Car Type" TextAlignment="Center" FontSize="30" VerticalAlignment="Top" Width="183" Height="61"/>
        <TextBlock HorizontalAlignment="Left" Text="Purchase Price"  TextAlignment="Center" FontSize="30" VerticalAlignment="Top" Margin="87,380,0,0" Width="226" Height="61" RenderTransformOrigin="3.948,-0.233"/>
        <TextBlock HorizontalAlignment="Left" Margin="87,487,0,0" Text="Model Year" TextAlignment="Center" FontSize="30" VerticalAlignment="Top" Height="65" Width="190" RenderTransformOrigin="3.283,-2.555"/>
        <TextBlock HorizontalAlignment="Left" Margin="87,584,0,0" Text="Mileage (Km)" TextAlignment="Center" FontSize="30" VerticalAlignment="Top" Height="43" Width="192"/>
        <Button x:Name="addingCar" Click="AddingCar_Click" Content="Add Car" FontSize="30" Margin="43,639,0,0" VerticalAlignment="Top" Height="56" Width="156"/>
        <Button x:Name="clearing" Click="Clearing_Click" Content="Clear" FontSize="30" Margin="224,639,0,0" VerticalAlignment="Top" Height="56" Width="134"/>
        <Button x:Name="updatingCar" Content="Update" FontSize="30" Margin="379,639,0,0" VerticalAlignment="Top" Height="56" Width="130"/>
        <ComboBox x:Name="carTypeInput" Margin="348,282,0,0" Width="191" Height="57"/>
        <ComboBox x:Name="modelYearInput" Margin="348,483,0,0" Width="191" Height="52"/>
        <TextBox x:Name="vinNumberInput" HorizontalAlignment="Left" Margin="348,88,0,0" Text="" FontSize="25"  VerticalAlignment="Top" Height="40" Width="191" RenderTransformOrigin="0.476,-1.383"/>
        <TextBox x:Name="carMakeInput" HorizontalAlignment="Left" Margin="348,176,0,0" Text="" FontSize="25"  VerticalAlignment="Top" Height="58" Width="191"/>
        <TextBox x:Name="purchasePriceInput" HorizontalAlignment="Left" Margin="348,380,0,0" Text="" FontSize="25"  VerticalAlignment="Top" Height="52" Width="191"/>
        <TextBox x:Name="mileageInput" HorizontalAlignment="Left" Margin="348,584,0,0" Text="" FontSize="15"  VerticalAlignment="Top" Height="32" Width="191"/>
        <Image x:Name="carImageOutput" HorizontalAlignment="Left" Height="429" Margin="1013,106,0,0" VerticalAlignment="Top" Width="226"/>
        <TextBlock x:Name="errorMessageOutput" HorizontalAlignment="Left" Margin="572,624,0,0" Text="" HorizontalTextAlignment="Center" FontSize="15" VerticalAlignment="Top" Width="641" Height="62"/>
        <ListView x:Name="lstCarDetailOutput" Margin="572,88,315,120"></ListView>

    </Grid>
</Page>


Перечисление:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Arsalan_Salam_991571527_A2
{
    public enum CarType
    {
        Odyssey,
        Rogue,
        Sienna
    }
}

Класс CarRepository:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Arsalan_Salam_991571527_A2
{
    class CarRepository
    {
        private List<Car> _carProducts = new List<Car>();
        //add product
        public void AddProduct(Car c)
        {
            try
            {
                //add a check to ensure product code is not duplicate
                if (GetByCode(c.VinNumber) != null)
                {
                    throw new Exception("Product already exists.");
                }

                _carProducts.Add(c);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        //search by product code
        public Car GetByCode(string productCode)
        {
            foreach (Car c in _carProducts)
            {
                if (c.VinNumber == productCode)
                {
                    return c;
                }
            }
            return null;
        }

    }
}


автомобиль класса:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Arsalan_Salam_991571527_A2
{
    class Car
    {
        private string _vinNumber;
        private string _carMake;
        private CarType _typeOfCar;
        private float _purchasePrice;
        private int _mileage;
        public override string ToString()
        {
            return $"{VinNumber}, {CarMake}, {TypeOfCar}, {PurchasePrice}, {Mileage}";
        }
        public Car(string vinNumber, string carMake, CarType typeOfCar, float purchasePrice, int[] modelYear, int mileage)
        {
            VinNumber = vinNumber; //using "this" as a reference to the invoking object
            CarMake = carMake; // invoke the property setter
            TypeOfCar = typeOfCar;
            PurchasePrice = purchasePrice;
            Mileage = mileage;
        }
        public Car(string vinNumber, string carMake, CarType typeOfCar, float purchasePrice, int modelYear, int mileage)
        {
            VinNumber = vinNumber;
            CarMake = carMake;
            TypeOfCar = typeOfCar;
            PurchasePrice = purchasePrice;
            Mileage = mileage;
        }
        public string VinNumber
        {
            get { return _vinNumber; }
            private set
            {
                if (string.IsNullOrEmpty(value))
                    throw new Exception("vin number code cannot be blank");
                _vinNumber = value;
            }
        }
        public string CarMake
        {
            get { return _carMake; }
            private set
            {
                if (string.IsNullOrEmpty(value))
                    throw new Exception("car make cannot be blank");
                _carMake = value;
            }
        }
        public CarType TypeOfCar
        {
            get { return _typeOfCar; }
            set
            {
                if (_typeOfCar.Equals(""))
                {
                    throw new Exception("Car type cannot be blank");
                }
                _typeOfCar = value;
            }
        }
        public float PurchasePrice
        {
            get
            {
                return _purchasePrice;
            }
            private set
            {
                if (value == 0)
                    throw new Exception("Purchase price cannot be blank or 0");
                _purchasePrice = value;
            }
        }
        public int Mileage
        {
            get { return _mileage; }
            set
            {
                if (_mileage == 0)
                {
                    throw new Exception("Mileage cannot be blank or 0");
                    _mileage = value;
                }
            }
        }
    }
}


Файл MainPage.язык XAML.в CS:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace Arsalan_Salam_991571527_A2
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public int[] modelYear = new int[] { 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 };
        public MainPage()
        {
            this.InitializeComponent();
            AddingEnumIntoComboBox(null);
            AddingIntArrayIntoComboBox(null);
        }
        public override string ToString()
        {
            return $"{ModelYear}";
        }
        //private List<Product> _products = new List<Product>();
        private CarRepository _carRepository = new CarRepository();
        private Car CaptureProductInfo()
        {
            string vinNumber = vinNumberInput.Text;
            string carMake = carMakeInput.Text;
            CarType typeOfCar = (CarType)carTypeInput.SelectedValue;
            float purchasePrice = float.Parse(purchasePriceInput.Text);
            int modelYear = Int32.Parse((string)modelYearInput.SelectedValue);
            int mileage = Int32.Parse(mileageInput.Text);
            Car c = new Car(vinNumber, carMake, typeOfCar, purchasePrice, modelYear, mileage);
            return c;
        }
        private void RenderProductInfo(Car car)
        {
            vinNumberInput.Text = car.VinNumber;
            carMakeInput.Text = car.CarMake;
            carTypeInput.SelectedItem = car.TypeOfCar.ToString();
            purchasePriceInput.Text = car.PurchasePrice.ToString();
            modelYearInput.SelectedItem = ModelYear.ToString();
            mileageInput.Text = car.Mileage.ToString();
        }
        private void ClearUI()
        {
            vinNumberInput.Text = "";
            carMakeInput.Text = "";
            carTypeInput.Items.Clear();
            purchasePriceInput.Text = "";
            modelYearInput.Items.Clear();
            mileageInput.Text = "";
            errorMessageOutput.Text = "";
        }
        private void AddingEnumIntoComboBox(object p)
        {
            foreach (var item in Enum.GetValues(typeof(CarType)))
            {
                var carTypeName = Enum.GetName(typeof(CarType), item);
                carTypeInput.Items.Add(carTypeName);
            }
        }
        private void AddingIntArrayIntoComboBox(object p) 
        {
            for (int i = 0; i < modelYear.Length; i++)
            {
                int year = modelYear[i];
                modelYearInput.Items.Add(year);
            }
        }
        public int[] ModelYear
        {
            get { return modelYear; }
            set
            {
                if (modelYear.Length == 0)
                    throw new Exception("Model year cannot be blank");
                modelYear = value;
            }
        }
        private void AddingCar_Click(object sender, RoutedEventArgs e)
        {
            string carType = carTypeInput.SelectedItem.ToString();
            string yearInput = modelYearInput.SelectedItem.ToString();
            try
            {
                //_products.Add(CaptureProductInfo());
                 Car c = CaptureProductInfo();
                _carRepository.AddProduct(c);
                lstCarDetailOutput.Items.Add(c);//the advantage of adding Product rather than a string?
            }
            catch (Exception ex)
            {
                errorMessageOutput.Text = ex.Message;
            }
            if (carType == "Honda" && yearInput == "2010")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2010Odyssey.jpg"));
            }
            else if (carType == "Honda" && yearInput == "2011")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2011Odyssey.jpg"));
            }
            else if (carType == "Honda" && yearInput == "2012")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2012Odyssey.jpg"));
            }
            else if (carType == "Honda" && yearInput == "2013")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2013Odyssey.jpg"));
            }
            else if (carType == "Honda" && yearInput == "2014")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2014Odyssey.jpg"));
            }
            else if (carType == "Honda" && yearInput == "2015")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2015Odyssey.jpg"));
            }
            else if (carType == "Honda" && yearInput == "2016")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2016Odyssey.jpg"));
            }
            else if (carType == "Honda" && yearInput == "2017")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2017Odyssey.jpg"));
            }
            else if (carType == "Honda" && yearInput == "2018")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2018Odyssey.jpg"));
            }
            else if (carType == "Honda" && yearInput == "2019")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2019Odyssey.jpg"));
            }
            else if (carType == "Honda" && yearInput == "2020") 
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2020Odyssey.jpg"));
            }
            else if (carType == "Sienna" && yearInput == "2010")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2010sienna.jpg"));
            }
            else if (carType == "Sienna" && yearInput == "2011")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2011sienna.jpg"));
            }
            else if (carType == "Sienna" && yearInput == "2012")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2012sienna.jpg"));
            }
            else if (carType == "Sienna" && yearInput == "2013")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2013sienna.jpg"));
            }
            else if (carType == "Sienna" && yearInput == "2014")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2014sienna.jpg"));
            }
            else if (carType == "Sienna" && yearInput == "2015")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2015sienna.jpg"));
            }
            else if (carType == "Sienna" && yearInput == "2016")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2016sienna.jpg"));
            }
            else if (carType == "Sienna" && yearInput == "2017")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2017sienna.jpg"));
            }
            else if (carType == "Sienna" && yearInput == "2018")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2018sienna.jpg"));
            }
            else if (carType == "Sienna" && yearInput == "2019")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2019sienna.jpg"));
            }
            else if (carType == "Sienna" && yearInput == "2020")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2020sienna.jpg"));
            }
            else if (carType == "Rogue" && yearInput == "2010")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2010Rogue.jpg"));
            }
            else if (carType == "Rogue" && yearInput == "2011")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2011Rogue.jpg"));
            }
            else if (carType == "Rogue" && yearInput == "2012")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2012Rogue.jpg"));
            }
            else if (carType == "Rogue" && yearInput == "2013")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2013Rogue.jpg"));
            }
            else if (carType == "Rogue" && yearInput == "2014")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2014Rogue.jpg"));
            }
            else if (carType == "Rogue" && yearInput == "2015")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2015Rogue.jpg"));
            }
            else if (carType == "Rogue" && yearInput == "2016")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2016Rogue.jpg"));
            }
            else if (carType == "Rogue" && yearInput == "2017")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2017Rogue.jpg"));
            }
            else if (carType == "Rogue" && yearInput == "2018")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2018Rogue.jpg"));
            }
            else if (carType == "Rogue" && yearInput == "2019")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2019Rogue.jpg"));
            }
            else if (carType == "Sienna" && yearInput == "2020")
            {
                carImageOutput.Source = new BitmapImage(new Uri($"ms-appx:///Assets/CardImages/2020Rogue.jpg"));
            }
        }
        private void Clearing_Click(object sender, RoutedEventArgs e)
        {
            ClearUI();
        }
    }
}



Ни один из этих кодов не генерирует ошибку, которую генерирует ошибка, когда я пытаюсь добавить автомобиль, он говорит, что не может привести объект 'System.Строка' to 'Arsalan_Salam_991571527_A2.CarType' в виде списка

Что я уже пробовал:

То, как я продвигался в решении этой проблемы, заключалось в проведении большого количества исследований и внедрении тех кодов, которые не решили эту проблему для меня.

Patrice T

Полное сообщение об ошибке, пожалуйста, включая позицию.

1 Ответов

Рейтинг:
10

Luc Pattyn

Что я уже пробовал:

Я обыскал весь интернет, а потом прочитал ваше сообщение об ошибке, и оно было очищено от вашей линии

CarType typeOfCar = (CarType)carTypeInput.SelectedValue;

это неприемлемо; вы не можете преобразовать строку в значение enum просто приведением, вам нужно вызвать Enum.Parse (пожалуйста, прочтите документацию, она где-то есть в интернете).

:)


Member 14876288

Не могли бы вы показать мне, как исправить эту проблему, написав код, большое вам спасибо

Luc Pattyn

Я предлагаю вам прочитать, что MSDN говорит о Enum.Parse, официальная страница документации включает в себя пример. Учитесь чему - то новому каждый день...