各位大虾,我在学习属性时候写了这个简单的例子:
class test1
{
private static int age;
public static int Age {
set { age = 34; }
get { return age; }
}
static void Main(string[] args)
{
Age = 45325;
Console.WriteLine("age:"+Age);
}
} 这样最后输出的就是age:34 可是要把 Age = 45325;注释掉 ,即为
class test1
{
private static int age;
public static int Age {
set { age = 34; }
get { return age; }
}
static void Main(string[] args)
{
//Age = 45325;
Console.WriteLine("age:"+Age);
}
}这样怎么结果就变成age:0了
class test1
{
private static int age;
public static int Age {
set { age = 34; }
get { return age; }
}
static void Main(string[] args)
{
Age = 45325;
Console.WriteLine("age:"+Age);
}
} 这样最后输出的就是age:34 可是要把 Age = 45325;注释掉 ,即为
class test1
{
private static int age;
public static int Age {
set { age = 34; }
get { return age; }
}
static void Main(string[] args)
{
//Age = 45325;
Console.WriteLine("age:"+Age);
}
}这样怎么结果就变成age:0了
然后获得的Age就是34
可是不是也有那些只可读的属性,不是就只有get么,我还有点小疑惑的是,为什么他的默认直是0,我不是设置为34么
直接调用还是初设化的值!
set 是设置值,可写入!get是获取值!
你这个明白了,那你是用类名调用一下看看!肯定就是在类里面设置的值!
不明白LZ到底想要什么样的结果呢?
你的意思是:即使 //Age = 45325; 结果也应该是age:34吗?
如果是的话,那你的写法是错的,age压根就没得到值,怎么能返回34?
还不如直接写成 private static int age;
public static int Age
{
get { return 34; }
}
很多只读属性获得的 是局部变量的值,而这些局部变量在其他方法操作中,已经发生了变化!!!age默认值为0你可以在set方法里面加Console.WriteLine(1); 看看是否执行这句
{
private static int age=34;
public static int Age {
set { age = value; }
get { return age; }
}
{
private static int age=34; public static int Age {
set { age = 34; }
get { return age; }
}
private static int age;
public static int Age {
set { age = value; }
get { return age; }
}
就好像餐厅点菜,你点(set)什么菜,就可以拿到(get)什么菜你的例子1:就好像餐厅只有一样菜,不管你点(set)什么,最后拿到(get)的都是那样菜例子2:虽然餐厅只要一样菜,但是你都不点,不进人家餐厅,你怎么会拿到菜呢如果你要直接不点菜(不调用set)就拿到菜的话,可以一开始就跟餐厅说,以后我来了不做说明就上那样菜,然后才会有你不点菜就能拿到菜的情况
private static int age=34;
public static int Age {
set { age = value; }
get { return age; }
}
理解有误。
关于类属性的get和set是如下解释:
get:获取私有变量age的值,若类中没有对age进行初始化,则默认age为0;
set:设置私有变量age的值,即实例化类test1后(假定实例为tst),进行tst.Age=“value”操作。
至于类中的属性Age,你可以认为它是一个方法的入口,环境会根据Age所处的上下文确定到底该执行get操作还是set操作:如果你讲Age赋给某一个变量,则执行get操作,取出实例中的age变量值赋给某一个变量;若你给Age赋值,则执行set操作,将值传给实例中的age变量。
给你个地址,上面有很多.net的电子书资源,你可以下载了看看:
.Net技术精品资料下载汇总:C#语言篇
{
private static int age;
public static int Age {
set { age = 34; }
get { return age; }
}
static void Main(string[] args)
{
//Age = 45325;
Console.WriteLine("age:"+Age);
}
}
lz 再注释掉//Age = 45325; 就不会执行set这个方法!只执行get;int类型得默认值就是0;
你初始化完成的时候 age=0.
如果你执行一次set,则age=34.
但是的测试代码没用执行set方法,所以age依然是0.使用get方法,不会调用set。而只是直接读取了age属性当时的值。如果你的意图是初始化就为34.那么添加一个私有字段比如
...
int a=34.
...
set { a = value;} //这个如果不需要写入值的话可以不写
get{ return a;}
...