C#字符串的限制长度 [英] C# limit length of a string

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

问题描述

我有以下课程:

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

上面的字段与数据库表中的字段匹配.在说 VendorName 的情况下,如何给它一个字段宽度?

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

VendorName 映射到数据库中的一个字段,该字段为 varchar(15)

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

推荐答案

您不能限制字符串的长度,但是可以将属性与后备字段一起使用以实现所需的结果:

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆