首页 > 解决方案 > 无法将类型“int”隐式转换为“bool”

问题描述

using System;

namespace Codes
{
    class Program
    {
        static void Main(string[] args)
        {
            String name = RandomNames();
            Console.Write(name);
            Console.ReadKey();
        }

        public static string RandomNames()
        {
            Random numGen = new Random();
            string vowel = "aeiou";
            string conso = "bcdfghjklmnpqrstvwxyz";
            int nameLen = numGen.Next(4,10);

            string result = "";
            for (int i = 0; i < nameLen; i++) 
            {
                if (i % 2) 
                {
                    result += vowel[numGen.Next(0, 4)]; // 4 is final index of vowel.
                } 
                else 
                {
                    result += conso[numGen.Next(0, 20)]; // 20 is final index of consonants.
                }
            }
            return result;
        }
    }

它说 if 语句中的“i”不能将类型“int”隐式转换为“bool”,我不知道这有什么问题,因为它已经是 for 循环中的 int

标签: c#for-loopif-statementintegerboolean

解决方案


i % 2是 int 类型,而不是 bool,C# 无法自动进行转换,所以只需尝试:

i % 2 != 0

推荐阅读