我正在接受下面Index out bounds error
的{{1}}。我有FullName property
课程和persondetails
课程,我正在使用data
试图调用此媒体资源。使用存储过程返回SqlDataReader
和firstname
值,然后我想创建一个属性来连接这些2,并且只能在我存储的过程中调用lastname
。
FullName
上课
persondetails
private string firstName;
private string lastName;
private string fullName;
public string FirstName
{
get { return firstName;}
set { set firstName = value;}
}
public string LastName
get { return lastName; }
set { set lastName = value; }
public string FullName
get { return lastName + "," + firstName;
}
public persondetails(string lastName, string firstName)
{
this.lastName = lastName;
this.firstName = firstName;
}
上课
data
存储过程只会从我的表中返回public List<Persondetails> getFullName()
{
// Do my sql connection stuff
List<Persondetails> persondetails = new List<Persondetails>();
Persondetails person;
try
{
// open connection
// specify "stored Procedure" (which returns firstname and lastname)
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
person = new Persondetails((
reader.GetString(reader.GetOrdinal("LASTNAME")));
reader.GetString(reader.GetOrdinal("FIRSTNAME")));
persondetails.Add(person);
}
reader.Close();
return persondetails;
}
// the rest of my method
和lastname
,其中包含2个单独的字段。我不想在这里进行连接,我想在我的属性中进行连接。
EDITED *** 工作守则
答案 0 :(得分:2)
由于在C#6.0中添加了类似的string
插值功能,我们可以将string
连接到下面
public string FullName => $"{firstName} {lastName}";
答案 1 :(得分:1)
您没有从名为“FullName”的存储过程返回的列是问题。这就是你得到错误的原因。
如果存储过程返回FirstName和LastName,则需要将它们存储在适当的属性中。
我希望你有一个方法可以从数据库中填充你的类......并且在这个类似的东西......
FirstName = reader.GetString(reader.GetOrdinal("FirstName")));
LastName = reader.GetString(reader.GetOrdinal("LastName")));
这将在您的类中填充您的FirstName和LastName ....然后您的FullName属性将起作用,因为它只是连接FirstName和LastName。
答案 2 :(得分:0)
您实际上并未在类构造函数中设置firstName
和lastName
字段,而是在构造函数和FullName
属性中复制代码。你需要做的是:
public string FullName
get { return this.lastName + "," + this.firstName;
}
public persondetails(string lastName, string firstName)
{
this.firstName = firstName;
this.lastName = lastName;
}
这将确保正确计算FullName
属性值。