c# - 如何定义相互依赖的属性

标签 c# .net validation properties dependencies

假设我有一个类有两个字符串类型的属性

  1. 提案 1
  2. 提案2

并且有以下限制

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

定义值相互依赖的属性的最佳方法是什么,并且对一个属性所做的更改应该触发另一个属性的 setter 属性?

最佳答案

您需要在属性 setter 中添加验证。

   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
       }
   }

关于c# - 如何定义相互依赖的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14123998/

相关文章:

c# - 是否可以在 WPF 的 Control 本身中添加航空效果?

asp.net - 如何从服务器错误 "the resource cannot be found"中删除版本信息

ios - 正则表达式在使用 MVC 设计模式的 iOS 应用程序中的什么位置?

ajax - 用于 ajax 表单的 ASP.NET MVC 2 服务器端验证

c# - nHibernate ICriteria 按多对多属性最小值排序

c# - 无法为 java 和 c# (winrt) 获得相同的 hmac_sha1 结果

.net - 解决 WCF 错误 : Metadata publishing for this service is currently disabled

validation - Google INVISIBLE reCaptcha + Bootstrap 4 验证器

c# - 向 DocumentViewer 显示 Tiff 图像时出错(WPF、C#)

c# - 克隆/复制现有的游戏对象及其子对象