C# limit length of a string

瘦欲@ 提交于 2021-02-04 19:41:08

问题


I have the following class:

public class VendorClass {         
    public int VendorID { get; set; }
    public string VendorName { get; set; }
}

The fields above match fields in the database table. In the case of say VendorName, how do I give it a field width ?

VendorName maps to a field in the database which is varchar(15)


回答1:


You can't limit the length of the string but you can use properties with backing fields to achieve the desired result :

public class VendorClass
{
    public int VendorID {  get; set; }

    private string _vendorName;

    public string VendorName
    {
        get { return _vendorName; }
        set
        {
            if (value.Length > 15)
            {
                _vendorName = value.Substring(0,15);                    
            } else { 
                _vendorName = value;
            }
        }
    }
}



回答2:


Strings in C# have almost-arbitrary length.

When loading from your database, it will automatically accommodate the actual string length. When saving to the database, your business logic, data layer or ORM (as appropriate) will need to ensure the proper maximum length.




回答3:


A string can't have a set length in C#. You will have to handle the db length through some other mechanism like validation. Can't really tell you more without more details.




回答4:


I would question why you would do this in c# code. However this link has a couple of ways around this. I suppose either truncation or taking a subsring is the best option. You could also make sure that the UI (or the model-view) takes care of details such as this.




回答5:


I am not sure exactly what you are asking, but if you want to know the maximum length of a string, this question can help you.

If you want to limit the number of characters entered, I would suggest that you use server-side validation and/or client-side validation.



来源:https://stackoverflow.com/questions/8248603/c-sharp-limit-length-of-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!