本文介绍了固定长度C#的字符串对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课,我想使用固定大小的字符串.固定大小的原因是该类序列化"为文本文件具有固定长度的值.我想避免在foreach值中写一个保护子句,而由类来处理.

I have a class wherein I want to use Strings with a fixed size.The reason for the fixed size is that the class "serializes" into a textfilewith values with a fixed length. I want to avoid to write foreach value a guard clause and instead have the class handle this.

所以我大约有30个属性,看起来像这样

So I have round about 30 properties which would look like this

    public String CompanyNumber
    {
        get
        {
            return m_CompanyNumber.PadLeft(5, ' ');
        }
        set
        {
            if (value.Length > 5)
            {
                throw new StringToLongException("The CompanyNumber may only have 5 characters", "CompanyNumber");
            }
            m_CompanyNumber = value;
        }
    }

我想拥有一个可以自行处理的String.目前,我有以下内容:

I would like to have a String that handles this by itself. Currently I have the following:

public class FixedString
{
    String m_FixedString;

    public FixedString(String value)
    {
        if (value.Length > 5)
        {
            throw new StringToLongException("The FixedString value may consist of 5 characters", "value");
        }
        m_FixedString= value;
    }

    public static implicit operator FixedString(String value)
    {
        FixedString fsv = new FixedString(value);
        return fsv;
    }

    public override string ToString()
    {
         return m_FixedString.PadLeft(5,' ');
    }
}

此解决方案的问题是我无法在编译时"设置字符串长度.

The problem I have with this solution is that I can't set the String length at "compile time".

如果最终看起来像这样,那将是理想的选择

It would be ideal if it would look something like this in the end

public FixedString<5> CompanyNumber { get; set; }

推荐答案

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

这篇关于固定长度C#的字符串对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:21