如何在 C# 中的一个函数中传回字符串和一个布尔值

本文关键字:一个 字符串 布尔值 函数 | 更新日期: 2023-09-27 18:34:25

所以我有这个函数

    public bool FileExists(string path, string filename)
    {
        string fullPath = Path.Combine(path, "pool");
        string[] results = System.IO.Directory.GetFiles(fullPath, filename, SearchOption.AllDirectories);
       return (results.Length == 0 ?  false : true);
    }

它返回 true 或 false 关于是否在目录及其所有子目录中找到文件......但是我也想传递字符串位置

这是我怎么称呼它的

            if (FileExists(location, attr.link))
            {
                FileInfo f = new FileInfo("string the file was found");

关于如何实现这一目标的任何想法?也许更改为列表或数组...任何想法

如何在 C# 中的一个函数中传回字符串和一个布尔值

你的意思是你只是想返回找到文件的所有出现位置吗?

你可以做:

public static string[] GetFiles(string path, string filename)
{
    string fullPath = Path.Combine(path, "pool");
    return System.IO.Directory.GetFiles(fullPath, filename, SearchOption.AllDirectories);   
}

并像这样使用:

var files = GetFiles(location, attr.link);
if (files.Any())
{
    //Do stuff
}

方法重命名为 TryFindFile 并因此提供签名:

public bool TryFindFile(string path, string filename, out string location)

该方法返回true如果找到文件,并将location设置为该位置,否则返回 false 并将location设置为 null 。如果有多个位置,则可以键入location作为string[]

添加您需要的参数。

bool FileExists(string path, string filename, out string somthElse)
{
   somthElse = "asdf";
   return true;
}

您可以将输出参数(out string[] 结果)传递给该方法并保留该方法,也可以更改方法并返回结果数组(并在调用方中检查 true 或 false)。

更便宜的做法是添加一个 out 参数。

各种方式 - 返回一个结构或具有两个字段的类,使用 out 关键字 modified,使用元组。

您可以使用out参数吗?

public bool FileExists(string path, string filename, out string location)
{
    string fullPath = Path.Combine(path, "pool");
    string[] results = System.IO.Directory.GetFiles(fullPath, filename, SearchOption.AllDirectories);
    var doesExist = (results.Length == 0 ?  false : true);
    location = fullPath;//or whatever it is
}

然后你可以这样称呼它

if (FileExists(path, filename, out location))
{
    //location now holds the path
}

有关out参数的更多信息,请参阅此处。