限制字符串的最大长度

Dil*_*o09 0 c# string unity-game-engine

我需要防止字符串超过一定长度,如果是,则截断字符串的最后一部分.

我正在使用GUI.TextField来自用户的字符串.

Yuc*_*uck 5

用属性包装它来处理截断:

public SomeClass {
    private const int MaxLength = 20; // for example
    private String _theString;

    public String CappedString {
        get { return _theString; }
        set {
            _theString = value != null && value.Length > MaxLength
                ? value.Substring(0, MaxLength)
                : value;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在任何需要实现它的类中应用它.只是继续private领域,常数和财产CappedString.