如果字符串的长度大于最大长度,是否有可以检查字符串并自动将三位省略号添加到字符串末尾的属性?
类示例:
public class Test() {
[AddEllipsis("...", MaxLength=30)]
String Name { get; set; }
}
示例:
Test t = new Test();
t.Name = "123456789012345678901234567890abc123";
Console.WriteLine(t.Name);
// Might look like "123456789012345678901234567..."
也希望动态添加。
答案 0 :(得分:1)
您可以为属性
实现自定义getterpublic class MyClass
{
private string _name;
public MyClass(string name)
{
_name = name;
}
public string Name => DoEllipsisTransform(_name, 30);
private static string DoEllipsisTransform(string value, int maxLength)
{
return value.Length > maxLength
? $"{value.Substring(0, maxLength - 3)}..."
: value;
}
}