无法在C#中设置和获取值

时间:2015-06-01 22:22:40

标签: c# asp.net

我正在尝试使用setter和getter。当我调试时,值被设置但是当我尝试检索时,它获得空值。

的Class1.cs

private string setMAX;
        public string SETMax
        {
            get
            {
                return setMAX;
            }
            set
            {
                setMAX = value;
            }
        }

private string value1;
        public string MaxValue
        {
            get
            {
                return value1;
            }
            set
            {
                value1= value;
            }
        }

Class2.cs

Class1.SETMax = Class1.value1; //This gets set

Class3.cs //当我调试时,首先Class1.cs和Class2.cs完成,然后它出现在Class3.cs

string max = Class1.SETMax; //I GET NULL here.

我不知道我在哪里错了。有人可以解释一下吗?

2 个答案:

答案 0 :(得分:0)

您正在引用File1作为实例。您可能正在引用不同的实例。你可能想要静态属性。

    private static string setMAX;
    public static string SETMax
    {
        get
        {
            return setMAX;
        }
        set
        {
            setMAX = value;
        }
    }

答案 1 :(得分:0)

我认为你混淆了一些事情,所以让我们从头开始

Class1.SETMax = Class1.value1; 
// for a start you are assigning a 
// private variable to a public one 
// via the Class definition I'm not even sure how that compiles.

看看这里是否对你有意义

// This is a Class definition
public class Class1 {
 public string SETMax {get; set;}
 public int MaxValue {get; set;}
}


// This is your application
public class MyApp{

 // this is a private field where you will assign an instance of Class1
 private Class1 class1Instance ;

 public MyApp(){
   //assign the instance in the constructor
        class1Instance = new Class1();
 }

 public void Run {
  // now for some fun

   class1Instance.SETMax = "Hello";
   Console.WriteLine(class1Instance.SETMax); // outputs "Hello"
   var localInstance = new Class1();
   localInstance.SETMax = class1Instance.SETMax;
   Console.WriteLine(localInstance.SETMax); // outputs "Hello"

}
 }