关于C#中 get set的疑惑,代码:
using System;
namespace com.cn
{
    class A
    {
        private string str;
      
        public string Str
        {
           get
            {
                return str;
            }
          set
            {
                if (value==null)
                    str = "Hello World!";
                else str = value;
                
            }
        }
   
       static void Main()
        {
           A a = new A();
       Console.WriteLine(a.str);}
    }}
value这个值从哪里来,上面代码执行的时候没有输出任何东西。我是想set方法内部设置属性值,麻烦高手解释一下。

解决方案 »

  1.   

    按照你写的方法A.Str = null;才能输出“Hello World”
      

  2.   

    你还没有set,所以输出时什么也没有
      

  3.   

    只有Str = ;的时候才能调用到内部的Set
      

  4.   

     A a = new A(); 
          Console.WriteLine(a.str); a.str="我是参数";
        你所说的 value 就是这个 “我是参数”。是一个隐式的。
      

  5.   

    你这个输出的肯定是啥都没的,因为Console.WriteLine(a.str); 调用的是get而不是set,所以这个时候的str是个null,输出当然什么都没,value是C#的属性这个语法里本身就有的一个变量,你如果在调用最后一句输出前使用a.Str = null;,这样的话是可以得到你要的结果,也就是输出hello world!
      

  6.   

    那怎么使用set方法?和java一样吗
      

  7.   

     A a = new A(); 
    在构造的时候,string str
    默认构造就是 str=null;所以
    Console.WriteLine(a.str); 
    就是Console.WriteLine(null); 
      

  8.   

    而这个“this”是外部放得到的自己的值
      

  9.   

    set 相当于重载了赋值操作,就是这个对象在等号左边出现的情况
    同理,get就是这个对象在等号右边出现的时候value 是一个隐含的参数