属性的字符串长度 [英] String Length for properties
本文介绍了属性的字符串长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨
如您在T-SQL中可能知道的那样,您可以为字符串/文本类型列指定长度,例如nvarchar(100)
.我想为C#类中的字符串分配最大长度.
Hi
as you may probably know in T-SQL one can assign a length for string/text type columns, for example nvarchar(100)
. I want to assign a maximum length for my strings in C# classes.
public class Customer
{
public string Name { get; set; }
public string Address { get; set; }
}
如何为字符串分配最大长度?
谢谢!
How can I assign a maximum length for strings?
Thank you!
推荐答案
好,
您可以为此做一个课程,
Ok,
You can Make a class for it,
public class LenghtString
{
public int Lenght { get; set; }
private string _Value;
public string Value
{
get
{
return _Value;
}
set
{
_Value = value;
if (_Value.Length > Lenght && Lenght != -1)
{
_Value = _Value.Substring(0, Lenght);
}
}
}
public LenghtString()
: this(-1)
{
}
public LenghtString(int lenght)
: this(lenght, string.Empty)
{
}
public LenghtString(string value)
: this(1, value)
{
}
public LenghtString(int lenght, string value)
{
Lenght = lenght;
Value = value;
}
}
现在,将属性定义为LenghtString:
Now, define your properties as LenghtString :
public class Customer
{
public LenghtString Name { get; set; }
public LenghtString Address { get; set; }
}
因此,您可以对其进行测试:
So, You may test it :
Customer c = new Customer()
{
Name = new LenghtString(20,"Shahin Khorshidia"),
Address = new LenghtString(50, "Bla Bla Bla Bla Bla Bla Bla Bla Bla Bla Bla Bla Bla Bla Bla Bla Bla Bla ...")
};
Console.WriteLine("{0} {1}",c.Name.Value, c.Address.Value);
祝你好运
Good Luck
将逻辑放入属性内.
Place the logic inside the property.
public string Name
{
get { return this._name; }
set
{
if(value.Length > MAXLEN)
this._name = value.Substring(0, Math.Min(value.Length, MAXLEN));
else this._name = value;
}
}
我希望这对您有用.
I hope this works for you.
这篇关于属性的字符串长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文