且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

固定长度C#的字符串对象

更新时间:2022-06-22 23:58:26

使 FixedString 使用大小作为构造函数参数,而不是值本身

Make FixedString take the size as a constructor parameter, but not the value itself

public class FixedString
{
   private string value;
   private int length;
   public FixedString(int length)
   {
      this.length = length;
   }

   public string Value 
   {
       get{ return value; }
       set
       {
            if (value.Length > length) 
            {
                 throw new StringToLongException("The field may only have " + length + " characters");
            }
           this.value = value; 
       }
   }
}

使用您的班级对其进行初始化,并在更改时设置 Value

Initilise it with your class, and just set the Value when it changes

public class MyClass
{
    private FixedString companyNumber = new FixedString(5);

    public string CompanyNumber
    {
        get{ return companyNumber.Value; }
        set{ companyNumber.Value = value; }
    }
}