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

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

问题描述

我只是想知道如何在 C# 中限制字符串的长度.

string foo = "1234567890";

说我们有那个.如何将 foo 限制为 5 个字符?

解决方案

C# 中的字符串是不可变的,从某种意义上说,这意味着它们是固定大小的.
但是您不能约束一个字符串变量只接受n个字符的字符串.如果你定义了一个字符串变量,它可以被分配任何字符串.如果截断字符串(或抛出错误)是您业务逻辑的重要组成部分,请考虑在您的特定类的属性设置器中执行此操作(这是 Jon 建议的,这是在 .NET 中对值创建约束的最自然方式).

如果您只是想确保不会太长(例如,将其作为参数传递给某些遗留代码时),请手动截断它:

const int MaxLength = 5;var name = "克里斯托弗";if (name.Length > MaxLength)name = name.Substring(0, MaxLength);//姓名 = "克里斯"

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

string foo = "1234567890";

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

解决方案

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).

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天全站免登陆