2010-08-29 87 views
13

如果我有一些类型的e.g:C#自动分配基于其他财产的属性值

public class SomeType //Generated by some codegen i won't to change that. 
{ 
    string C { get; set; }   
} 

public class AnotherType : SomeType 
{ 
    string A { get; set; } 
    string B { get; set; } 
} 

是否有可能自动分配性质C?例如,当属性A和B被赋值,或者当我将这个类型转换为某种其他类型,或者以某种方式?

基本上,我想执行一些逻辑,以便在属性值A和B被填充时的某个点根据值A和B自动分配属性C.

是否有任何其他方式来做到这一点,而不是使用标准属性?

我在想,当我可以将类型AnotherType转换为SomeType时,我可能会做一些魔法之王,但我不能实现隐式运算符,因为我可能会将此转换逻辑“从A + B转换为C”,因为编译器不会不允许相关类型的隐式运算符。

现在只有办法我看到它是删除继承和实现AnotherType的SomeType转换的隐式运算符,但邪恶在这种情况下,我需要复制类型AnotherType中类型SomeType的所有属性,我需要手动更改类型AnotherType SomeType得到改变的时间。

回答

15

这可以使用自动实现的属性。你可以使用B的二传手分配一个值到C:

public class SomeType 
{ 
    public string A { get; set; } 
    public string C { get; set; } 

    private string _b; 
    public string B 
    { 
     get { return _b; } 
     set 
     { 
      // Set B to some new value 
      _b = value; 

      // Assign C 
      C = string.Format("B has been set to {0}", value); 
     } 
    } 
} 
+0

我有继承我不能修改属性 – Kuncevic 2010-08-29 08:43:01

+0

你没有修改名称或属性的类型,只是他们的getter和setter的实现不应该打破你的继承。 – 2010-08-29 08:44:25

+0

@bigb:我对你的评论感到困惑。你是说A&B,也可能是C,它是你正在继承并且不能修改的类中的自动属性? – 2010-08-29 08:50:06

3

不,我知道的,你就必须按如下方式使用沼泽标准属性(柜面你只知道自动属性)

public class SomeType 
{ 
    string _A; 
    string _B; 
    string _C; 

    public string A { get{return _A;} set{ _A = value; _C = _A + _B; } } 
    public string B { get{return _B;} set{ _B = value; _C = _A + _B; } 
    public string C { get{return _C}; } 
} 
+0

我无法使用标准属性 – Kuncevic 2010-08-29 08:44:48

+3

@bigb,自动执行的属性**是**标准属性。它们只是被编译成标准属性的语法糖,所以是的,你可以使用**标准属性,你已经做到了。 – 2010-08-29 08:47:48

+0

是的,我知道,我更新了更多的细节问题 – Kuncevic 2010-08-29 11:38:44

4

你想设置C,还是只能得到它?如果你并不需要能够设置的值,那么我想你想要这样的:

public class MyClass 
{ 
    private string _a = "not set"; 
    private string _b = "not set"; 

    public string A 
    { 
     get { return _a; } 
     set { _a = value; } 
    } 

    public string B 
    { 
     get { return _b; } 
     set { _b = value; } 
    } 

    public string C 
    { 
     get 
     { 
      if (_a != "not set" && _b != "not set") 
       return "not set"; 
      else 
       return "set"; 
     } 
    } 
} 

这里的访问属性的一个简单的例子是依赖于其他属性:

public class MyClass 
{ 
    private double[] MyArray = new double[5]; 

    public int NumElements 
    { 
     get 
     { 
      return MyArray.Length; 
     } 
    } 
} 
+0

谢谢。我只需要“获取”变量,并且总是有意义的把这种逻辑放在变量上,无论如何都会自动改变,因为从理论上讲,影响属性('A'或'B')可能会影响许多其他变量 – AlbatrossCafe 2016-02-05 21:11:41