如何强制执行字符串中允许的最大和最小字符数

时间:2014-11-18 18:14:14

标签: c# string properties

我想限制我的字符串,所以你必须至少输入3个字符和最多10个字符。这可以在下面的代码中使用吗?

main.cs:

class Program
{   
    static void Main(string[] args)
    {
        Something hello = new Something();
        string myname;

        Something test = new Something();
        myname = Console.ReadLine();
        test.Name = myname;
    }
}

具有属性的类:

class Okay : IYes
{
    private string thename;

    public string Name
    {
        get {return thename;}
        set {thename = value;} //what to put here???
    }
}

3 个答案:

答案 0 :(得分:2)

setter可能不是最好检查的地方。你应该在输入点进行检查:

  string myname = "";
  while (myname.Length<3 || myname.Length >10)
  {
    Console.WriteLine("Please enter your name (between 3 and 10 characters");
    myname = Console.ReadLine();
  }
  test.Name = myname;

显然你可以采取一些措施使这个用户更友好:在第一次失败后可能会有不同的消息,某种方式退出循环等等。

答案 1 :(得分:1)

试试这个: -

public string Naam
        {
            get { return thename; }
            set
            {
                if (value.Length >= 3 && value.Length <= 10)
                    thename = value;
                else
                    throw new ArgumentOutOfRangeException();
            } 
        }

答案 2 :(得分:0)

class Okay : IYes
{
    private string name;

    public string Name
    {
        get { return name; }
        set
        {
            if (value == null) throw new ArgumentNullException("Name");
            if (value.Length < 3 || value.Length > 10) 
                throw new ArgumentOutOfRangeException("Name");
            name = value;
        }
    }
}

如果字符串太长,你也可以截断字符串,而不是通过取(最多)前10个字符来抛出异常:

class Okay : IYes
{
    private string name;

    public string Name
    {
        get { return name; }
        set
        {
            if (value == null) throw new ArgumentNullException("Name");
            if (value.Length < 3) throw new ArgumentOutOfRangeException("Name");
            name = string.Join("", value.Take(10));
        }
    }
}

private static void GenericTester()
{
    Okay ok = new Okay {Name = "thisIsLongerThan10Characters"};
    Console.WriteLine(ok.Name);
}

// Output:
// thisIsLong