繁体   English   中英

是否可以基于另一个属性将set属性的默认值分配给set?

[英]Is it possible to assign set the default value of a class property based on another property?

我有一个具有Value属性和CharToRead列表,我试图找出一种将CharToRead自动设置为Value.Length

我认为这可以通过构造函数来完成,但是由于我有一个通用类,所以我什至无法创建构造函数。

类:

  public class HeaderType<T>
    {
        public string FieldTag { get; set; }
        public string FieldName { get; set; }
        public string Value { get; set; }
    }

public class HeaderTypeEnq<T> : HeaderType<T>
{
    public string Mandatory { get; set; }
    public string CharacterType { get; set; }
    public string FixedLength { get; set; }
    public int Position { get; set; }
    public int MaxLength { get; set; }
    public int CharToRead { get; set; }    
}

清单:

  List<HeaderTypeEnq<dynamic>> PNListEnq = new List<HeaderTypeEnq<dynamic>>();
            PNListEnq.Add(new HeaderTypeEnq<dynamic>() { FieldTag = "PN", FieldName = "Segment Tag", Value = "PN", Mandatory = "Y", CharacterType = "A/N", Position = 0, MaxLength = 04, FixedLength = "Y", CharToRead= ?  }); // replace ? with length of Value

然后,在消费者类中,您可以仅使用Value.Length。 但是,如果您仍然想使用CharToRead,这将是解决方案:

public class HeaderTypeEnq<T> : HeaderType<T>
{
    public string Mandatory { get; set; }
    public string CharacterType { get; set; }
    public string FixedLength { get; set; }
    public int Position { get; set; }
    public int MaxLength { get; set; }
    public int CharToRead
    {
        get
        {
            if (string.IsNullOrEmpty(Value))
            {
                return 0;
            }
            return Value.Length;
        }
    }
}

我不知道根据您告诉我们的方法执行此操作的好方法,但是您肯定可以在通用类上使用构造函数,因此您可以执行类似的操作(当然,可以使用所需的任何参数) :

public class HeaderTypeEnq<T> : HeaderType<T>
{
    public HeaderTypeEnq(string value)
    {
        this.Value = value;
        this.CharToRead = this.Value.Length;
    }

    public string Mandatory { get; set; }
    public string CharacterType { get; set; }
    public string FixedLength { get; set; }
    public int Position { get; set; }
    public int MaxLength { get; set; }
    public int CharToRead { get; set; }    
}

那你可以用

PNListEnq.Add(new HeaderTypeEnq<dynamic>("PN")
    {
        FieldTag = "PN",
        FieldName = "Segment Tag",
        Mandatory = "Y",
        CharacterType = "A/N",
        Position = 0,
        MaxLength = 04,
        FixedLength = "Y"
    });

除此之外,假设您希望能够修改所讨论的属性(该属性使用自定义逻辑排除了仅用于getter的属性),那么我认为唯一的其他选择就是修改属性的setter逻辑,但这似乎会很快变得混乱。

private string _value;
public string Value
{
    get
    {
        return this._value;
    }
    set
    {
        this._value = value;
        this.CharToRead = value.Length;
    }
}

当然,这也将涉及修改基类(至少使该属性为virtual ),这可能是可行的,也可能是不可行的。

“由于我有一个通用类,所以我什至无法创建构造函数。”

没错,您可以创建泛型类型的实例,并为此也构造一个构造函数:

public HeaderTypeEnq<T>(string value) {
    this.Value = value;
    this.CharToRead = this.Value.Length;
}

暂无
暂无

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

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