繁体   English   中英

不能从另一个类调用方法

[英]Can't call a method from another class

我尝试调用myCar.FormatMe() ,但它没有显示。 我不知道为什么。 有什么建议?

using System;
namespace SimpleClasses
{
    class Program
    {
        static void Main(string[] args)
        {
            Car myCar = new Car();
            myCar.Make = "BMW";      
            myCar.FormatMe();
            Console.ReadLine();
        }
    }

    class Car
    {
        public string Make { get; set; }
        public string FormatMe()
        {
            return string.Format("Make: {0}", this.Make);
        }

    }
}

非常感谢。

您的代码中没有输出

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car();
        myCar.Make = "BMW";      
        Console.WriteLine(myCar.FormatMe());
    }
}

class Car
{
    public string Make { get; set; }
    public string FormatMe()
    {
        return string.Format("Make: {0}", this.Make);
    }

}

孤立的字符串和阅读而不是写作

您正在从FormatMe()函数返回一个字符串,但实际上并没有对它做任何事情:

myCar.FormatMe(); // This will return your value, but it isn't being stored

此外,您正在调用Console.ReadLine()方法,该方法实际上期望来自用户的输入而不是将其输出给用户。

存储您的变量并将其写出

考虑将其存储在变量中或将其作为参数直接传递给Console.WriteLine()方法以作为输出发送:

// This will store the results from your FormatMe() method in output
var output = myCar.FormatMe();
// This will write the returned string to the Console
Console.WriteLine(output);
// You can now read it here
Console.ReadLine();

或者 :

// Write the output from your FormatMe() method to the Console
Console.WriteLine(myCar.FormatMe());
// Now you should be able to read it
Console.ReadLine();

例子

您可以在此处查看此操作的交互式示例,其输出演示如下:

在此处输入图片说明

要么将您的函数调用包装在对Console.WriteLine()的调用中,要么让FormatMe()做同样的事情。

您对函数调用所做的只是返回一个字符串,但不对其进行任何操作,例如将其分配给变量或将其作为参数传递给另一个函数。 因此,它“什么都不做”,因为你没有对它做任何事情。

您应该从FormatMe()获取值或简单地打印它:

static void Main(string[] args)
{
     Car myCar = new Car();
     myCar.Make = "BMW";           
     Console.ReadLine(myCar.FormatMe());
}

抱歉来晚了; 我不确定是否接受这种答案; 如果方法不对,请见谅。

让我们借助一个例子来看看这个问题。 也就是说,您要向指定的人(这里是car )索取一些东西( here it is a formatted string )。 问题是给我一个格式化的刺( FormatMe() )。 一切都很好 - 到此为止。

下一步是什么? 如果一切正常(意味着函数中没有问题)给你格式化的字符串,这个人会给你结果。 这在你的情况下也没关系(函数完美地返回了格式化的字符串)。

这个时候你需要做什么? 您需要从相应的人那里收集产品。不幸的是,您忘记收集它们,但您正试图将其交付给另一个人。 这在你的情况下发生。

那么该怎么办? 在将产品交付到控制台之前,您需要收集产品,格式化的字符串。 那是:

string formattedString =myCar.FormatMe(); // collecting formatted string
Console.WriteLine(formattedString); // delivering it to the console

或者您可以在前往控制台的途中收集它们,如下所示:

Console.WriteLine(myCar.FormatMe()); // delivering it to the console

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM