C#根据其他属性值自动分配属性

Kun*_*vič 18 c# c#-4.0

如果我有一些类型,例如:

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; }
}
Run Code Online (Sandbox Code Playgroud)

是否可以自动分配属性?例如,当属性A和B被分配时,或者当我将此类型转换为其他类型时,或者其他方式?

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

有没有其他方法可以做到这一点而不是使用标准属性?

我认为当我将类型AnotherType转换为SomeType时,可以做一些魔法之王,但是我无法实现隐式运算符,我可以把这个转换逻辑"从A + B转换为C",因为编译器不允许隐式相关类型的运算符.

现在只有我看到它是删除继承并实现AnotherType到SomeType转换的隐式运算符,但在这种情况下的邪恶我需要复制类型AnotherType类型SomeType的所有属性,我需要每次当SomeType获取时手动更改类型AnotherType改变.

Dar*_*rov 24

这可以使用自动实现的属性.您可以使用B的setter为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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


gkr*_*ers 6

你想要能够设置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";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是访问依赖于另一个属性的属性的更简单示例:

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

    public int NumElements
    {
        get
        {
            return MyArray.Length;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Pau*_*eld 5

不是我所知道的,你必须使用如下的沼泽标准属性(如果你只知道自动属性)

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}; }
}
Run Code Online (Sandbox Code Playgroud)

  • @bigb,自动实现的属性**是**标准属性.它们只是被编译成标准属性的语法糖,所以是的**你可以使用**标准属性,你已经这样做了. (3认同)