【问题标题】:Is there is a way to call a object from a method?有没有办法从方法中调用对象?
【发布时间】:2020-10-23 22:43:42
【问题描述】:

C# 新手想知道是否可以从方法中调用对象

我必须继续打字吗

Console.WriteLine(James.name); Console.WrtieLine(James.age);

对于我制作的每个新对象?

对不起,如果这是一个简单的问题。 :(

示例:

https://i.stack.imgur.com/6GVXV.png

命名空间示例 {

class Dog
{
    public string name;
    public int age;
    
    public Dog(string _name, int _age)
    {
    name = _name;
    age = _age;
    }
}

class Program
{
    public static void Main()
    {
    Dog James = new Dog("James", 4);

    Dog Daniel = new Dog("Daniel", 2);
    }

    //I know from thispart it does not work but is there a way to make a similar result?
    
    status(James);
    status(Daniel);
}


public static void status(thisdog)
{
    Console.WriteLine(thisdog.name);
    Console.WrtieLine(thisdog.age);
}

【问题讨论】:

  • 应该是void status(Dog thisdog) - 你错过了类型
  • 了解如何在 Dog 上覆盖 ToString
  • 非常感谢你们,我会调查的

标签: c# object methods call


【解决方案1】:

您的代码应该可以正常工作,您只需要修复一些错误(内联评论):

class Program
{
    public static void Main()
    {
        Dog James = new Dog("James", 4);
        Dog Daniel = new Dog("Daniel", 2);

        status(James); // <-- This needs to be inside Main
        status(Daniel);
    }

     // This needs a type for the parameter and needs to be inside Program
    public static void status(Dog thisdog)
    {
        Console.WriteLine(thisdog.name);
        Console.WriteLine(thisdog.age); // <-- fixed typo
    }
}

【讨论】:

  • 非常感谢您的友好回答! (´·ω·`) 现在像魅力一样工作
【解决方案2】:

欢迎来到 Stackoverflow.com!自从 C# 以来已经有一段时间了,但我会试一试。

我已经更改了你的代码,所以它应该可以工作。

class Program
{
    public static void Main()
    {
        // 1.
        Dog james = new Dog("James", 4);
        Dog daniel = new Dog("Daniel", 2);
    
        // 2.
        status(james);
        status(daniel);
    }

    // 3.
    public static void status(Dog thisdog)
    {
        Console.WriteLine(thisdog.name);
        Console.WrtieLine(thisdog.age);
    }
}

让我们来看看吧:

  1. 命名:有一定的规则要遵循。例如大写和小写。对于类和方法,您始终应该选择大写,例如Dog。对于属性和对象,您应该始终使用小写字母,例如 Dog james。当然还有更多规则,但我不记得了。
  2. 从方法中调用方法。据我记得这会起作用。
  3. 您忘记将类添加到方法参数中。

我希望这对您有所帮助。如果有任何问题,请告诉我......正如我所说:已经有一段时间了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 2010-11-14
    • 2019-06-30
    相关资源
    最近更新 更多