在对象列表中打印字符串值

时间:2017-11-16 14:50:37

标签: c# arrays list object

我目前正在尝试创建一个地址簿应用程序,该应用程序将某些人员数据保存在一个对象中,然后将其添加到列表中。我目前正在制作一种方法来尝试在提示时列出数据,但信息没有显示,是否有人知道如何解决此问题?

namespace AddressBook
{
    class Student : Person
    {
    public String StudentID { get; set; }
    public String grade { get; set; }

    public List<Student> studentList = new List<Student>();

 public void addStudent(string firstName, string lastName, string address, string city, string country, string postcode, string StudentID, string grade )
    {
        Student student = new Student();
        student.firstName = firstName;
        student.lastName = lastName;
        student.address = address;
        student.city = city;
        student.country = country;
        student.postcode = postcode;
        student.StudentID = StudentID;
        student.grade = grade;
        studentList.Add(student);
    }

 public void listStudentData()
    {
        String fname ="", lname="", add="", city="", country="", post="", id="", grd = "";
        String[,] index = { { "First name: ", "Last Name: ", "Address: ", "City: ", "Country: ", "Postcode: ", "StudentID: ", "Grade: " }, { fname, lname, add, city, country, post, id, grd }, };
        for (int i = 0; i < studentList.Count; i++)
        {
            fname = (studentList[i].firstName.ToString());
            lname = (studentList[i].lastName.ToString());
            add = (studentList[i].address.ToString());
            city = (studentList[i].city.ToString());
            country = (studentList[i].country.ToString());
            post = (studentList[i].postcode.ToString());
            id = (studentList[i].StudentID.ToString());
            grd = (studentList[i].grade.ToString());
            Console.WriteLine(index[0, i] + index[1,i]);
        }
        Console.WriteLine("");
    }



}

}

我要打印的格式是 &#34;名字:John&#34; &#34;姓氏:史密斯&#34;等

但目前的格式是: &#34;名字:&#34;

非常感谢任何建议

4 个答案:

答案 0 :(得分:2)

你真的过于复杂化,只是为了列出学生。这很容易:

public void ListStudentData()
{
    foreach (Student student in studentList)
    {
        Console.WriteLine("First Name: {0}", student.firstName);
        Console.WriteLine("Last Name: {0}", student.lastName);
        Console.WriteLine("Address: {0}", student.address);
        ...
        ...
        ...
    }
}

此外,通常作为标准命名约定,方法名称应以大写字母开头。

答案 1 :(得分:1)

<div class="row ng-scope" ng-repeat="field in $ctrl.getFields() as fields" ng-if="$index % 2 == 0"> <!-- ngRepeat: i in [$index, $index + 1] --><!-- ngIf: fields[i] --><nc-form-group-template ng-repeat="i in [$index, $index + 1]" ng-if="fields[i]" section-id="a1gg0000002ARlMAAW" guid="a1gg0000002ARlMAAW338C1B4330ED4993A7B3178099C70517" field="fields[i]" context-id="a38g0000001juVQAAY" ,="" enable-field-access="$ctrl.enableFieldAccess" class="ng-scope ng-isolate-scope"> <div class="form-group col-xs-6"> <nc-field-label-template section-id="a1gg0000002ARlMAAW" field="$ctrl.field" inline-help-text="" label="Other Loan Purpose" is-required="$ctrl.field.isRequired" enable-field-access="$ctrl.enableFieldAccess" class="ng-isolate-scope"> <div class="row content-label"> <div class="col-xs-12"> <span ng-show="$ctrl.inlineHelpText" popover="popover" data-toggle="popover" data-content="" class="fa fa-info-circle slds-show--inline ng-hide" data-original-title="" title=""> </span> <label ng-bind="$ctrl.label" class="form-control-static input-sm slds-show--inline ng-binding" ng-class="{'is-required': $ctrl.isRequired, 'pull-left': $ctrl.enableFieldAccess}">Other Loan Purpose</label> <span class="slds-p-left--medium"> <!-- ngIf: !$ctrl.field.isVisible && $ctrl.enableFieldAccess --> <span class="slds-assistive-text">This field will be hidden from the user.</span> </span> <!-- ngIf: $ctrl.enableFieldAccess --> </div> </div> </nc-field-label-template> <!-- ngIf: !$ctrl.isReadOnly() --><nc-editable-field-template ng-if="!$ctrl.isReadOnly()" section-id="a1gg0000002ARlMAAW" guid="a1gg0000002ARlMAAW338C1B4330ED4993A7B3178099C70517" field="$ctrl.field" context-id="a38g0000001juVQAAY" class="ng-scope ng-isolate-scope"> <div class="row"> <div class="col-xs-12 content-body"> <nc-editable-field section-id="a1gg0000002ARlMAAW" guid="a1gg0000002ARlMAAW338C1B4330ED4993A7B3178099C70517" field="$ctrl.field" context-id="a38g0000001juVQAAY" class="ng-isolate-scope"> <!-- ngIf: $ctrl.fieldType.isTextarea($ctrl.field.fieldType, $ctrl.field.isHtmlFormatted) --><textarea ng-if="$ctrl.fieldType.isTextarea($ctrl.field.fieldType, $ctrl.field.isHtmlFormatted)" ng-model="$ctrl.field.value" ng-change="$ctrl.onChange()" ng-required="$ctrl.field.isRequired" ng-class="{ 'input-sm': true, 'form-control': true, 'nc-pristine': $ctrl.getPristine(), 'nc-not-pristine': $ctrl.getNotPristine() }" class="ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched"></textarea><!-- end ngIf: $ctrl.fieldType.isTextarea($ctrl.field.fieldType, $ctrl.field.isHtmlFormatted) -->成为studentList课程的成员似乎是一种奇怪的设计选择。它属于您的程序或表单的成员。

但针对具体问题,请看这一行:

Student

此时,所有这些属性变量(String[,] index = { { "First name: ", "Last Name: ", "Address: ", "City: ", "Country: ", "Postcode: ", "StudentID: ", "Grade: " }, { fname, lname, add, city, country, post, id, grd }, }; fname等)都是空字符串。您稍后为这些变量分配值:

lname

但是,这不会改变数组的内容!

我将仅使用fname = (studentList[i].firstName.ToString()); //... 变量来解释发生的事情。 fname是对内存中字符串对象的引用。最初它指的是一个空字符串。您还有fname数组,其中包含许多引用,您可以将其中一个引用设置为引用与index引用相同的空字符串对象。但是,这是该引用的副本fnamefname位置都指向内存中的同一对象,但它们是独立变量。现在,您为index分配一个新值。 fname变量引用内存中的不同字符串。但是,fname中的位置没有改变,仍然指的是它在开头时的空字符串。

要解决此问题,您可能想要做的是重载index类的.ToString()方法(以及Student和其他派生类)。这看起来像这样:

Person

这有很多原因(其中最重要的是帮助您检查调试器中的Student对象),但是对于这个问题,它允许您重写public override string ToString() { return string.Format("First name: {0}\nLast Name: {1}\nAddress: {2}\nCity: {3}\nCountry: {4}\nPostcode: {5}\nStudentID: {6}\nGrade: {7}\n", firstName, lastName, address, city, country, postcode, StudentID, grade); } 看起来像这样:

listStudentData()

在一个更大,更复杂的程序中,您可能需要几种不同的方式来显示人,而不是(或除了)覆盖public void listStudentData() { foreach(var student in studentList) { Console.WriteLine(student); } } 之外,您将添加一个ToString()静态类,将PersonFormatterPerson转换为具有各种输出的字符串的公共方法的数量。

答案 2 :(得分:1)

注意:这不是最佳解决方案,但我只是希望您了解原始代码有什么问题,以及如果您将来发现类似问题,如何纠正错误。请参阅其他答案,了解完成任务的最有效方法。

初始化数组时,要打印的所有变量的值都是空字符串。

String fname ="", lname="", add="", city="", country="", post="", id="", grd = "";

如果要继续使用当前方法,则需要做的是使用for循环中的实际值更新变量。

像这样:

public void listStudentData()
{
    String fname ="", lname="", add="", city="", country="", post="", id="", grd = "";
    String[,] index = { { "First name: ", "Last Name: ", "Address: ", "City: ", "Country: ", "Postcode: ", "StudentID: ", "Grade: " }, { fname, lname, add, city, country, post, id, grd }, };
    for (int i = 0; i < studentList.Count; i++)
    {
        index[1,0] = studentList[i].firstName.ToString();
        index[1,1] = studentList[i].lastName.ToString();
        index[1,2] = studentList[i].address.ToString();
        index[1,3] = studentList[i].city.ToString();
        index[1,4] = studentList[i].country.ToString();
        index[1,5] = studentList[i].postcode.ToString();
        index[1,6] = studentList[i].StudentID.ToString();
        index[1,7] = studentList[i].grade.ToString();

        for (int j = 0; j < 8; j++)
        {
            Console.WriteLine(index[0, i] + index[1,j]);
        }        
    }
    Console.WriteLine("");
}

答案 3 :(得分:1)

发布我的解决方案,您可能会发现它很有用。

我在原始示例中看到缺少基类Person类,在此处提供:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string PostCode { get; set; }


    public override string ToString()
    {
        return $"First name: {FirstName}, Last name: {LastName}, Address: {Address}, City: {City}, Country: {Country}, Post code: {PostCode}";
    }
}

您可以看到我们正在重写ToString()方法以返回预期的文字表示。正如其他人所指出的那样,在C#(常见约定)中对公共属性使用PascalCase表示法总是更好。接下来是派生的Student类:

public class Student : Person
{
    public String StudentID { get; set; }
    public String Grade { get; set; }

    public override string ToString()
    {
        return $"{base.ToString()}, Student ID: {StudentID}, Grade: {Grade}";
    }
}

这里我们添加了StudentID和Grade属性,并再次覆盖了Object类的ToString()方法。覆盖使用我们之前编写的基类的ToString()方法。

最后,打印出一个Student对象列表的示例:

static void Main(string[] args)
{
    var students = new List<Student>();
    students.Add(
        new Student
        {
            FirstName = "John",
            LastName = "Doe",
            Address = "43 North West",
            City = "Capetown",
            Country = "South Africa",
            PostCode = "12345",
            Grade = "A+",
            StudentID = Guid.NewGuid().ToString("N")
        });

    foreach (Student student in students)
    {
        Console.WriteLine(student);
    }
}

输出是:

First name: John, Last name: Doe, Address: 43 North West, City: Capetown, Country: South Africa, Post code: 12345, Student ID: 975d7bf2e80f4406b14119f8fbc3018e, Grade: A+