首页 > 解决方案 > 如何将 `|` 操作数应用于字符串?

问题描述

我在这里遇到了这行代码的问题......为什么会提示我这个错误?我收到一条错误消息,说"Operator '|' cannot be applied to operands of type 'bool' and 'string'如何检查我的驻留变量是否不等于我在 if 语句中列出的这 2 个字符串?

catch (ArgumentException)
            {
                if (age > 16 | age > 80)
                {
                    Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
                }
                if (residency != "OH" | "MI")
                {
                    Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
                }
            }

如果您想更好地了解我要执行的内容,这里是完整的代码。

class Program
    {
        static void Main(string[] args)
        {
            CarInsurance create = new CarInsurance();
            Console.Write("Enter the age of the driver: ");
            int age = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter the state the driver lives in: ");
            string residence = Convert.ToString(Console.ReadLine());
            create.PremiumCalculate(age, residence);
        }
    }
    class CarInsurance
    {
        public int driverAge { get; set; }
        public string residency { get; set; }
        public int totalPremium;

        public int GetPremium()
        {
            return totalPremium;
        }
        public void PremiumCalculate(int age, string residency)
        {
            int premiumOhio = 100;
            int premiumMichigan = 250;
            try
            {
                if (residency == "MI")
                {
                    int total = (100 - age) * 3 + premiumMichigan;
                    Console.WriteLine("Your premium is {0}", total.ToString("C"));
                }
                if (residency == "OH")
                {
                    int total = (100 - age) * 3 + premiumOhio;
                    Console.WriteLine("Your premium is {0}", total.ToString("C"));
                }
            }
            catch (ArgumentException)
            {
                if (age > 16 | age > 80)
                {
                    Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
                }
                if (residency != "OH" | "MI")
                {
                    Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
                }
            }
        }
    }

标签: c#classtry-catchor-operator

解决方案


您应该在两个条件之间应用它,而不是值。笔记

if (residency != "OH" || residency != "MI")

但是请注意,此条件将始终返回true。您可能打算使用&&

if (residency != "OH" && residency != "MI")

推荐阅读