簡體   English   中英

將對象傳遞給另一個類?

[英]Passing an object to another class?

我最近一直在研究構造函數,Im目前正在嘗試將一個對象傳遞給另一個類文件,Im的執行方式如下所示:

class Program
{
    static void Main(string[] args)
    {
        Class1 objPls = new Class1();

        objPls.nameArray[0] = "jake";
        objPls.nameArray[1] = "tom";
        objPls.nameArray[2] = "mark";
        objPls.nameArray[3] = "ryan";

        Echodata form2 = new Echodata(objPls);
    }
}

class Class1
{
    public string[] nameArray = new string[3];
}

class Echodata
{
    public Class1 newobject = new Class1();

    public Echodata(Class1 temp)
    {
        this.newobject = temp;
    }

    // so now why cant i access newobject.namearray[0] for example?
}

問題是我無法訪問該對象以進入陣列。

有哪些傳遞對象的方法? 有人告訴我,這是一種大致的實現方式,並且進行了一段時間的嘗試無濟於事。

不知道這是什么,你不能做。 例如,經過此修改的代碼可以運行,或者至少可以編譯。

   class echodata
    {
        public Class1 newobject = new Class1();

        public echodata(Class1 temp)
        {
            this.newobject = temp;
        }

        // so now why cant i access newobject.namearray[0] for example?
        // What kind of access do you want?

        public void method1()
        {
            newobject.nameArray[0] = "Jerry";
        }

    }

您有一個問題,嘗試在數組的第四個索引上設置“ ryan”字符串時,代碼將引發錯誤。 您最初將數組設置為長度3。

在EchoData類中,您可以毫無問題地訪問nameArray對象,但是您必須在方法或構造函數中對其進行訪問。 您不能操縱這些內容以外的內容。

請記住,在EchoData類中,您將看不到在Main方法中設置的值。

很難說,因為您還沒有提供完整的,可編譯的示例,也沒有確切解釋“無法訪問”的含義(出現錯誤了嗎?是什么?)

但是,我的猜測是您正在嘗試根據代碼從類級別訪問傳入的對象字段。

即,您正在嘗試這樣做:

class Echodata
{
    public Class1 newobject; // you don't need to initialize this

    public Echodata(Class1 temp)
    {
        this.newobject = temp;
    }

    newobject.newArray[0] = "Can't do this at the class level";
}

您只能從成員方法中訪問nameArray。

class Echodata
{
    public Class1 newobject; // you don't need to initialize this

    public Echodata(Class1 temp)
    {
        this.newobject = temp;
    }

    public void DoSOmething() {
        newobject.newArray[0] = "This works just fine";
    }
}

暫無
暫無

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

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