Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#从函数返回值时出错_C#_.net_Function_Ref - Fatal编程技术网

c#从函数返回值时出错

c#从函数返回值时出错,c#,.net,function,ref,C#,.net,Function,Ref,我尝试使用一个方法或函数来创建所需的目录树,并将新路径返回到调用过程 但我无法编译它 我收到一个错误无法将方法组“localAttachmentsPath”转换为非委托类型字符串。 这是我的代码-我做错了什么?有没有更好的方法来实现这一点 private string localAttachmentsPath(ref string emailAttachmentsPath) { string sYear = DateTime.Today.

我尝试使用一个方法或函数来创建所需的目录树,并将新路径返回到调用过程

但我无法编译它

我收到一个错误
无法将方法组“localAttachmentsPath”转换为非委托类型字符串。

这是我的代码-我做错了什么?有没有更好的方法来实现这一点

        private string localAttachmentsPath(ref string emailAttachmentsPath)
        {

            string sYear = DateTime.Today.Year.ToString();
            string sMonth = DateTime.Now.ToString("MMMM");
            string sDirectoryDate = DateTime.Today.ToString("dd.MM.yyyy");

            if (!Directory.Exists(emailAttachmentsPath))
            {
                Directory.CreateDirectory(emailAttachmentsPath);

            }

            emailAttachmentsPath = emailAttachmentsPath + "\\" + sYear;
            if (!Directory.Exists(emailAttachmentsPath))
            {
                Directory.CreateDirectory(emailAttachmentsPath);
            }

            emailAttachmentsPath = emailAttachmentsPath + "\\" + sMonth;
            if (!Directory.Exists(emailAttachmentsPath))
            {
                Directory.CreateDirectory(emailAttachmentsPath);
            }

            emailAttachmentsPath = emailAttachmentsPath + "\\" + sDirectoryDate;
            if (!Directory.Exists(emailAttachmentsPath))
            {
                Directory.CreateDirectory(emailAttachmentsPath);
            }

            //localAttachmentsPath = emailAttachmentsPath;
            return localAttachmentsPath;

        }

只需指定要返回的值,如下所示:

return emailAttachmentsPath;
我还建议您从参数中删除
ref
关键字

进一步阅读


看起来问题在于:

return localAttachmentsPath;

这是一个函数,我想您应该用函数名以外的名称声明一个局部变量。

如果您使用的是
ref string emailAttachmentsPath
,则不需要返回任何字符串

您可以将返回类型设为
void
,并在传递变量时删除
return
语句
emailAttachmentsPath
作为引用变量,因此它将从调用方更新,而无需返回语句

您的方法应该如下所示:

private void localAttachmentsPath(ref string emailAttachmentsPath)
{

//your code

//no return statement

}

你想还什么?你现在所做的只是返回一个对你自己函数的引用,而不是一个值。如果您想返回emailAttachmentsPath,只需输入“return emailAttachmentsPath”,就不需要将函数名设置为返回值(这是VB语法吗?),而且您知道,
CreateDirectory
已经创建了整棵树,如果您传递了完整路径,则不需要按子文件夹创建它的子文件夹…@Bartdude:谢谢,现在我不需要一个函数:)实际上,我几乎用它写了一个答案。实际上,您可以用一行代码替换整个函数,以获得相同的效果。这里还有一条建议:当你不确定的时候,读一下文档,或者试试看。。。我想这会为你节省一些时间;-)