首页 新闻 会员 周边

C#成员变量

0
悬赏园豆:30 [已解决问题] 解决于 2016-03-04 11:24

我现在需要在类里面定义一个变量,在类里面的一个方法中赋值,然后在另一个方法中使用,请问要怎么定义,给点关键代码

jinggege的主页 jinggege | 初学一级 | 园豆:5
提问于:2015-11-26 11:03
< >
分享
最佳答案
0

C#里面的字段和属性。理解清楚就好了。一般来说字段是私有的 private,属性定义为public,通过属性给存取字段的值。

 

public Class Student
{
    private string studentName; //定义私有字段,也叫成员变量
    
    //获取字段的值
    public string GetStudentName()
    {
        return this.studentName;
    }

    //给字段赋值
    public void SetStudentName(string name)
    {
        this.studentName=name;
    }
}



然而,C#中可以直接自定义字段的时候搞定:

public class Student
{
        private string studentName;

        public string StudentName
        {
            get { return studentName; }
            set { studentName = value; }
        }
}


你甚至可以:

public class Student
{
        private string studentName{get; set;}
}

后面两种方法,会自动生成对应点的属性。

用的时候:

  Student objStudent=new Student();//实例化一个学生对象

  objStudent.SetStudentName("张三");//给该学生的姓名赋值

  string name=objStudentName.GetStudentName(); //获取该学生的姓名,并保存到变量name中
收获园豆:10
SharpCJ | 菜鸟二级 |园豆:242 | 2015-11-27 22:04
其他回答(2)
0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //在别的地方使用

            A a = new A();
            a.F();
            Console.WriteLine(a.T);
        }
    }


    //定义一个变量
    class A
    {

        //定义一个变量
        public string T;

        //在方法中赋值 
        public void F()
        {
            this.T = "HelloWorld";
        }
    }
}
收获园豆:20
需要格局 | 园豆:2145 (老鸟四级) | 2015-11-26 11:14
0
public class People
    {
//设置变量
        public void SetName()
        {
            this._name = "张三";
        }
        public string GetName()
        {
            return _name;
        }
        //定义变量
        private string _name;
    }
public class Main{
     People p = new People();
//获取变量
       p.GetName();
}
凝冰 | 园豆:685 (小虾三级) | 2015-11-26 11:18
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册