簡體   English   中英

如何從一個類到另一個類獲取變量值?

[英]How to acess variable value from one class to another class?

我想從一個類訪問另一個類的字符串。 我使用了屬性方法如下 -

Myclass.cs

public class MyClass
{
    private string _user;
    public string user
    { get { return this._user; } set { this._user = value; } }

}

consumption.aspx.cs

我正在為函數中的用戶賦值

MyClass m = new MyClass();
m.user = "abc"

現在,當我嘗試在我的另一個函數中使用此值時,在分配此值之后調用該函數

RawDal.cs

MyClass m = new MyClass();
string x = m.user;

我得到空的價值......怎么做?

正如在評論中已經提到的那樣,您正在創建兩個獨立的MyClass實例,其結果簡化為:

int a;
a = 3;
int b;
Console.WriteLine("a: " + b); //<-- here it should be obvious why b is not 3

您可以通過以下三種方式解決此問題:

1)對第二次調用使用相同的MyClass實例,但在這種情況下,您需要在同一范圍內或將實例傳遞給新范圍。

2)使屬性/成員靜態:

public class MyClass
{
    public static string User { get; set; } //the "static" is the important keyword, I just used the alternative property declaration to keep it shorter
}

然后,您可以通過MyClass.User訪問相同的User值。

3)使用單身人士:

public class MyClass
{
    private static MyClass instance = null;
    public static MyClass Instance 
    {
        get
        {
            if(instance == null)
                instance = new MyClass();
            return instance;
        }
    }

    public string User { get; set; }
}

然后,您可以通過MyClass.Instance.User訪問它。

可能還有一些解決方案,但這些是常見的解決方案。

您沒有使用相同的實例。 嘗試

public class MyClass
{
    private string _user;
    public string user
    { get { return this._user; } set { this._user = value; } }

}

public string YourFunction()
{
   MyClass m = new MyClass();
   m.user = "abc"
   return m.user;

}

如果你想要返回的只是一個字符串嘗試類似的東西

string x = YourFunction();

暫無
暫無

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

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