5

我想从一个类访问一个字符串到另一个类。我使用的属性方法如下 -

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;

我得到空值......怎么办?

4

2 回答 2

12

正如评论中已经提到的,您正在创建两个单独的实例,MyClass其结果简化为:

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

您可以通过 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
}

然后您可以User通过MyClass.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.

可能还有更多解决方案,但这些是常见的解决方案。

于 2013-08-21T12:46:56.083 回答
5

您没有使用相同的实例。尝试

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();
于 2013-08-21T12:30:01.123 回答