2012-04-10 56 views
1

我有一个简单的场景,其中AnotherTest值基于Test值。这在大多数情况下都能正常工作,所以只要我提供Test,我一定会很容易得到AnotherTest多个访问器在c中具有相同的值#

public sealed class Transaction { 
    public string Test { get;set; } 
    public string AnotherTest{ 
     get { 
      int indexLiteryS = Test.IndexOf("S"); 
      return Test.Substring(indexLiteryS, 4); 
     } 
    } 
} 

但是我希望能够还setAnotherTest值,并能无需提供Test价值读它。这可能吗?所以有两种类型的get,它的设置方式。我知道我可以创建3rdTest,但我有一些方法使用AnotherTest和其他字段,我将不得不编写该方法的重载。

编辑:

我读了一些银行提供的文件。我把它切成块,把一些东西放在Test的值中,并且交易的其他所有字段(AnotherTest和类似)都会自动填充。 但是后来我想从SQL读取已经处于良好格式的事务,因此我不需要提供Test以获取其余字段。我想用set设置这些字段,然后可以使用get而不设置Test值。

+3

你的'AnotherTest' getter目前是递归的,并且还提到'LiniaTransakcjiString' - 这两个是否意味着实际使用'Test'? – 2012-04-10 16:45:42

+0

是既测试(复制/粘贴),但插入了错误的值 – MadBoy 2012-04-10 16:46:37

+0

那么它在逻辑上意味着*设置AnotherTest没有一个测试值?这并没有帮助你没有给我们真正的指示这些属性是什么意图代表。 – 2012-04-10 16:48:11

回答

4

是的,就像这样:

public string Test { get; set; } 

public string AnotherTest 
{ 
    get 
    { 
     if(_anotherTest != null || Test == null) 
     return _anotherTest; 

     int indexLiteryS = Test.IndexOf("S") 
     return Test.Substring(indexLiteryS, 4); 
    } 
    set { _anotherTest = value; } 
} 
private string _anotherTest; 

这为

return (_anotherTest != null || Test == null) 
    ? _anotherTest 
    : Test.Substring(Test.IndexOf("S"), 4); 
1

我认为这会做你想要做什么的getter也可以表示为:

public sealed class Transaction { 
    public string Test { get;set; } 
    public string AnotherTest{ 
     get { 
      if (_anotherTest != null) 
      { 
       return _anotherTest; 
      } 
      else 
      { 
       int indexLiteryS = Test.IndexOf("S"); 
       return Test.Substring(indexLiteryS, 4); 
      } 
     } 
     set { 
      _anotherTest = value; 
     } 
    } 
    private string _anotherTest = null; 
} 
0

我会建议把问题转过来。

这听起来像是你在处理一个大的领域和子领域。相反,如何将这些子领域推广到领域,并在访问大领域时构建/解构大领域。

+0

我正在从银行的文件中解构为我提供的大字段。当它以干净的格式保存到SQL中时,尝试读取SQL并构建与银行发送信息相同的类型似乎不是一个好主意,因为它看起来过于夸张,代码也不必要。 – MadBoy 2012-04-10 16:57:11

相关问题