c# - 默认对象访问器(Object = a 而不是 Object.value = a),在内部限制字符串
问题描述
我正在尝试创建一个可以用来代替标准 String 对象的 String 对象。因为我将经常使用这个“LimitedString”,所以我的计划是创建一个包含 Int/MaxLength 和 String/Value 的对象。
因为它将被大量使用,并且在创建对象后唯一重要的是值(它在内部处理长度),我希望能够使用 InitializedObject = String() 而不是 InitializedObject 设置它的“值”。值 = 字符串()
到目前为止我所尝试的一切都给了我错误。这是我在 C# 中不能做的事情吗?
这是对象的代码:
public class LimitedString{
private int _maxlength;
private string _value;
public LimitedString(int length, string text = "")
{
_maxlength = length;
_value = text;
}
private string Value
{
get { return _value; }
set { _value = _value.Truncate(_maxlength); }
}
//Operators
public static implicit operator string(LimitedString ls)
{
return ((ls == null) ? null : ls.Value);
}
public static implicit operator LimitedString(string text)
{
//Needs to return the LimitedString Object That is being manipulated
return text == null ? null : new LimitedString(text.Length, text);
}}
我也在使用这个字符串扩展
public static string Truncate(this string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Length <= maxLength ? value : value.Substring(0, maxLength);
}
任何建议将不胜感激,请记住,在初始化对象后,它必须保留其最大长度,并且字符串(值)需要仅通过对象即可访问。我相信 string = Object, 正在工作,但我不能让它反过来工作。