如何定义彼此依赖的属性

Ani*_*aul 3 .net c# validation dependencies properties

假设我有一个类有两个string类型的属性

  1. PROP1
  2. PROP2

并且有以下限制

  1. 如果Prop2值为"Test2",则Prop1不能等于"Test1"
  2. 如果Prop1值为"Test11",则Prop2不能等于"Test22"
  3. 如果Prop2 ="Test222",则设置Prop1 ="Test111"

定义其值彼此依赖的属性的最佳方法是什么,以及在一个属性中进行的更改应该触发另一个属性的setter属性?

Til*_*lak 5

您需要在属性设置器中添加验证.

   string prop1;
   string prop2;

   string Prop1 
   {
      get { return prop1;}
      set 
      {
         if (!( Prop2 == "Test2" && value == "Test1"))
         {
             Prop1 = value;
          }
         ... Add other condition here
      }
   }

   string Prop2
   {
      get { return prop1;}
      set 
      {
         // set Prop2 based on Prop1
       }
   }
Run Code Online (Sandbox Code Playgroud)