如何在 属性 中设置字符串的限制

How to set the limit of string in property

我运行没有想法我不知道在这儿做什么 我需要让字符串 Course Name 在长度超过 100 个字符时根据用户的输入输出一条消息

public string CourseName
    {
        get { return courseName; }
        set
        {
            if (courseName>value)//I can't fix this one
            {
                Console.WriteLine("You have typed more than 50 characters");
            }
            else
            {
                courseName = value;
            }
        }
    }

要检查一个字符串有多少个字符,请检查它的 .Length -属性.

因此 value.Length > 100 检查传入的 value 是否超过 100 个字符。

public string CourseName
{
    get { return courseName; }
    set
    {
        if (value != null && (value.Length > 50))
        {
            Console.WriteLine("You have typed more than 50 characters");
        }
        else
        {
            courseName = value;
        }
    }
}

要检查字符串的长度是否超过最大值,您需要使用字符串 class 的 Length 属性,它包含字符串的字符长度,例如:

if (value.Length > 50)
{
    Console.WriteLine("You have typed more than 50 characters");

    return;
}
courseName = value;

请注意,您还需要处理 null 输入,sins 字符串是可空类型。

所以你可能想做这样的事情:

if (value == null)
{
    Console.WriteLine("The course name can not be null.");
}
else if (value.Length > 50)
{
    Console.WriteLine("You have typed more than 50 characters");
}
else
{
    courseName = value;
]