我打算创建自己的字符串类,但是它将提供最大长度。 我们称之为“ lString”。 我想像代码中的“ string”类一样使用“ lString”。但是我可以为其设置最大长度。
例如,应构建以下代码:
// 1- No maxlength provided, so the object will be created.
lString mylString1 = "0123456789";
// 2- maxlength provided, so it will be checked, and then created.
lString mylString2 = new lString("0123456789", 10);
// 3- This time only maxlength provided, so it will be a string object with maxLength.
lString mylString3 = new lString(20);
// At the end, I should be able to use it like a regular strings:
mylString3 = mylString1 + mylString2;
// Below should throw exception at RunTime, because it will be over 20)
mylString3 = mylString1 + mylString2 + mylString1 + mylString2;
答案 0 :(得分:2)
实现一个基本的字符串类非常简单,该类具有对普通字符串的隐式运算符:
public class LimitedString
{
private readonly string value;
private readonly long maxLength;
public LimitedString(string value, long maxLength = long.MaxValue)
{
if(value != null && value.Length > maxLength)
throw new InvalidOperationException("Value is longer than max length");
this.value = value;
this.maxLength = maxLength;
}
public override string ToString()
{
return value;
}
public override int GetHashCode()
{
return value.GetHashCode();
}
public override bool Equals(object o)
{
if(o is LimitedString)
return value == ((LimitedString)o).value;
return false;
}
public static implicit operator LimitedString(string str)
{
return new LimitedString(str);
}
public static implicit operator String(LimitedString ls)
{
return ls.value;
}
}
然后您的前两个案例按预期工作:
LimitedString myString1 = "0123456789";
LimitedString myString2 = new LimitedString("0123456789", 10);
但是,使第三个示例工作的唯一方法是这样的:
LimitedString myString3 = new LimitedString(myString1 + myString2 + myString1 + myString2, 20); // Throws exception
重新分配该值后,最大长度的规范将丢失,因此您不能这样做:
LimitedString myString3 = new LimitedString(20); // This is fine - you could have a constructor that just takes the max length.
myString3 = myString1 + myString2 + myString1 + myString2; // but here you're re-assigning.