簡體   English   中英

有沒有辦法從方法中調用 object ?

[英]Is there is a way to call a object from a method?

C# 的新手想知道是否有辦法從方法中調用 object

我必須繼續打字嗎

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

對於我制造的每個新 object?

對不起,如果這是一個簡單的問題。 :(

例子:

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);
}

歡迎訪問 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);
    }
}

讓 go 通過它:

  1. 命名:有一定的規則要遵循。 例如大寫和小寫。 對於類和方法,你總是應該選擇像Dog這樣的大寫字母。 對於屬性和對象,您應該始終使用像Dog james這樣的小寫字母。 當然還有更多的規則,但我不記得了。
  2. 從方法中調用方法。 據我記得這會奏效。
  3. 您忘記將 class 添加到方法參數中。

我希望這對您有所幫助。 如果有任何問題,請告訴我......正如我所說:已經有一段時間了。

您的代碼應該可以正常工作,您只需要修復一些錯誤(內聯評論):

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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM