繁体   English   中英

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

[英]C# Automatically assign property based on other property values

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

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

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

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

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

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

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

这可以使用自动实现的属性。 您可以使用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);
        }
    }
}

你想要能够设置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;
        }
    }
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM