为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Main Method中返回具有字符串参数的 bool 方法

如何在 Main Method中返回具有字符串参数的 bool 方法

C#
潇湘沐 2022-08-20 15:55:12
我创建了一个带有字符串参数的布尔方法。虽然值为 true,但它有效,但在 false 上,它给出一个错误。在 main 方法中调用 bool 方法时,它不接受来自 bool 方法的相同字符串参数。public static bool init_access(string file_path){    int counter = 0;    file_path = @"C:\Users\waqas\Desktop\TextFile.txt";    List<string> lines = File.ReadAllLines(file_path).ToList();    foreach (string line in lines)    {        counter++;        Console.WriteLine(counter + " " + line);    }    if (File.Exists(file_path))    {        return (true);    }    return false;}如果文件确实存在,它应该返回 true,否则它应该返回 false。
查看完整描述

4 回答

?
湖上湖

TA贡献2003条经验 获得超2个赞

您首先读取该文件,然后检查它是否存在。当然,你必须使用另一种方式:


public static bool init_access(string file_path)

{

    if (!File.Exists(file_path))

    {

        return false;

    }


    int counter = 0;

    string[] lines = File.ReadAllLines(file_path);

    foreach (string line in lines)    

    {   

        counter++;

        Console.WriteLine(counter + " " + line);

    }


    return true;

}


查看完整回答
反对 回复 2022-08-20
?
富国沪深

TA贡献1790条经验 获得超9个赞

一般来说(或偏执的)案例文件可以在检查后出现/取消(创建或删除)。捕获异常 () 是肯定的,但速度较慢:File.ExistsFileNotFoundException


public static bool init_access(string file_path)

{

    try 

    {

        foreach (string item in File

              .ReadLines(file_path)

              .Select((line, index) => $"{index + 1} {line}"))

            Console.WriteLine(item);


        return true;

    }

    catch (FileNotFoundException) 

    {

        return false;

    }

}


查看完整回答
反对 回复 2022-08-20
?
撒科打诨

TA贡献1934条经验 获得超2个赞

试试这个:


    public static bool init_access(string file_path)

    {

        if (File.Exists(file_path))

        {

            int counter = 0;

            foreach (string line in File.ReadAllLines(file_path))

            {

                counter++;

                Console.WriteLine(counter + " " + line);

            }


            return true;

        }


        return false;

    }


查看完整回答
反对 回复 2022-08-20
?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

正如Rango所说,是的,您必须首先检查该文件是否存在。如果您喜欢较小的解决方案:


public static bool init_access(string file_path)

{

    if (File.Exists(file_path))

    {

        var counter = 0;

        File.ReadAllLines(file_path).ToList().ForEach(x => Console.WriteLine(counter++ + " " + x));


        return true;

    }


    return false;

}


查看完整回答
反对 回复 2022-08-20
  • 4 回答
  • 0 关注
  • 99 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号