类变量:
一个类的所有不同对象只能共享一个副本,
class StudentDetails
{
static Int rollNumber;
/*...*/
}
实例变量:
每个对象都有其自己的实例变量的个人副本。因此,跨不同对象的实例变量可以具有不同的值,而跨不同对象的类变量只能具有一个值。
class StudentDetails
{
Int rollNumber;
/*...*/
}
Class和Instance变量都是Member变量
,
实例(或非静态)变量
同一个实例变量可以具有与该类的引用数一样多的值,因此,如果您具有这样的类并且对其进行了多次实例化,则可以更改每个实例变量(名称)的值。每个对象实例(foo和bar):
public class Fancyclass
{
//this is an instance variable
string name;
public static void Main(string[] args)
{
Fancyclass foo = new Fancyclass();
Fancyclass bar = new Fancyclass();
foo.name = "My Name";
bar.name = "Your Name";
Console.WriteLine(foo.name);
Console.WriteLine(bar.name);
}
}
输出:
My Name
Your Name
类(或静态)变量
另一方面,只能通过限定的名称空间访问类(或静态)变量,因此,您实际上总是在访问相同的值(实际上,您不能通过引用的/ instance / object访问它)。类。如果尝试,它将显示错误)。您需要完整的“地址”:
public class ClassExample
{
//class (or static) variable
static string name;
public static void Main(string[] args)
{
ClassExample foobar = new ClassExample();
//this will show an error
foobar.name;
//instead you access it this way
ClassExample.name = "PUFF!!"
Console.WriteLine(ClassExample.name);
}
}
输出:
PUFF!!
,
在类中定义为字段的所有内容都是关联的实例。在下面的类中,rollnumber,studentName都是实例关联的。
Class StudentDetails
{
int rollNumber;
string studentName;
}
StudentDetails student = new StudentDetails();
如果您在类中定义了静态字段,则它将与该类相关联。
Class StudentDetails
{
int rollNumber;
string studentName;
static int StudentClassNumber = 123
}
此处,静态字段StudentClassNumber与该类相关联,而不与该实例相关联。
如果要实例化实例化的StudentDetails,则需要在类定义中定义一个非默认构造函数。
Class StudentDetails
{
int rollNumber;
string studentName;
public StudentDetails(int rollnumber,string studentName)
{
this.rollNumber = rollnumber;
this.studentName = studentName;
}
}
StudentDetails firststudent= StudentDetails (19236,"Thomas");
本文链接:https://www.f2er.com/2725915.html