如何在方法中调用方法?

How to call a method in a method?

我在这里尝试 return 来自方法 MapFinder() 的字符串,并使用来自方法 return 的字符串在 MapTracker() 的另一个条件下使用.

public String MapFinder()
{
    if ((Map.Width == 8 && Map.Height==8))
    {
        return "DefaultMap";
    }
    else
        return "Something Different";
}

public String MapTracker()
{
    if(StringFromMapFinder == "DefaultMap");
    {
        return "Hello DefaultMap";
    }
    else
    {
        return "Hello StrangeMap";
    }

您可以在 MapTracker()

中调用方法 MapFinder()
public string MapFinder()
{
    if ((Map.Width == 8 && Map.Height == 8))
    {
        return "DefaultMap";
    }
    return "Something Different";
}

public string MapTracker()
{
        // call the method, include the "()"
        if(MapFinder() == "DefaultMap");
        {
               return "Hello DefaultMap";
        }

        return "Hello StrangeMap";
}               

你几乎可以完全按照你描述的那样做,你只是少了一些。经过一些最小的修复后,您的代码将是:

public String MapFinder()
{
    if ((Map.Width == 8 && Map.Height==8))
    {
        return "DefaultMap";
    }
    else
        return "Something Different";
}

public String MapTracker()
{
    if( MapFinder() == "DefaultMap" ) // <- change
    {
        return "Hello DefaultMap";
    }
    else
    {
        return "Hello StrangeMap"; // <- change
    }
}

我已经标记了更改。我做了三个:

  • 修正了打字错误:你在第一个 if 中有一个 ; 而不是 )
  • 修正了打字错误:您在 strangemap
  • 中有一个未闭合的引号 "
  • 我已将 StringFromMapFinder 替换为 方法调用

但是,通常情况下,您更愿意将该调用的结果存储在某处并稍后检查它:

public String MapTracker()
{
    String mapFinderResult;
    mapFinderResult = MapFinder();
    if( mapFinderResult == "DefaultMap" )
    {
        return "Hello DefaultMap";
    }
    else
    {
        return "Hello StrangeMap";
    }
}

在这里,我创建了一个名为 mapFinderResult 的变量,我调用了该方法并将结果存储在该变量中,然后在 if 中我使用该变量来检查返回的内容。这个更长的版本与之前的版本相同,只是结果存储在变量中而不是直接在 if 条件中使用。

我不会详细描述它,因为我需要写一个很长的课程。请获取一些 C# 教程并进一步阅读 methods calling methodsusing variables.