C#:限制字符串的长度? [英] C#: Limit the length of a string?

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

问题描述

我只是简单地想知道我怎么能限制在C#中的字符串的长度。

I was just simply wondering how I could limit the length of a string in C#.

string foo = "1234567890";

说,我们有。如何限制富说,5个字符?

Say we have that. How can I limit foo to say, 5 characters?

推荐答案

在C#中的字符串是不变的,在某种意义上就意味着他们是固定大小。结果
然而,你不能约束一个字符串变量只接受正字符串。如果你定义一个字符串变量,它可以分配的任何的字符串。如果截断字符串(或抛出错误)是你的业务逻辑的重要组成部分,可考虑在特定类的属性setter这样做(这是乔恩建议,并且它在.NET价值创造约束的最自然的方式)。

Strings in C# are immutable and in some sense it means that they are fixed-size.
However you cannot constrain a string variable to only accept n-character strings. If you define a string variable, it can be assigned any string. If truncating strings (or throwing errors) is essential part of your business logic, consider doing so in your specific class' property setters (that's what Jon suggested, and it's the most natural way of creating constraints on values in .NET).

如果你只是想确认是不是太长(例如,通过它,当作为参数传递给一些遗留code),手动截断它:

If you just want to make sure isn't too long (e.g. when passing it as a parameter to some legacy code), truncate it manually:

const int MaxLength = 5;


var name = "Christopher";
if (name.Length > MaxLength)
    name = name.Substring(0, MaxLength); // name = "Chris"

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

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