看源代码刚学到的,当属性的set块中还有其它调用或较复杂的操作时,不要重复设置对象的属性。道理很简单啊,还是贴段代码吧使用set时需要考虑的一点,代码演示的是怎样做是否重复的判断而不是重现上面描述的情景.
    class EntryPoint
    {
        [STAThread]
        
static void Main(string[] args)
        {
            Test test 
= new Test();
            test.Name 
= "yicone";
            test.Name 
= "yicone";
            test.Name 
= "yic";
            Console.ReadLine();
        }
    }

    
public class Test
    {
        
int i = 1;
        
public string name;
        
public string Name
        {
            
get{return name;}
            
set
            {
                
if(value == Name)
                {
                    Console.WriteLine(
"第{0}次set name属性失败!", i++);
                    Console.WriteLine(
"原因:与当前Test类的实例的Name属性值相同,不需要更改");
                    
return;
                }
                name 
= value;
                Console.WriteLine(
"第{0}次set name属性成功", i++);
            }
        }
    }

p.s. 调整了措词,以避免不必要的误会.

相关文章:

  • 2022-12-23
  • 2022-03-07
  • 2021-07-09
  • 2021-07-31
  • 2021-08-22
  • 2021-10-06
  • 2021-09-18
猜你喜欢
  • 2022-03-06
  • 2022-03-03
  • 2021-11-24
  • 2022-12-23
  • 2022-02-25
  • 2021-06-17
  • 2022-12-23
相关资源
相似解决方案