【问题标题】:C#/VB - change the value of a property of a class (object) [duplicate]C#/VB - 更改类(对象)的属性值[重复]
【发布时间】:2016-11-02 15:46:37
【问题描述】:

我有一个Students 列表,如下所示

public List<Students> StudentsClassCollection;

Students 类如下所示:

public class Students
{
    public string StudentName;
    public bool Passed;
}

我想访问其中一名学生并将Passed 的值从false 更改为true。 我该怎么做?

【问题讨论】:

  • StudentName 是您的学生之间的唯一值吗?如果不是,您打算如何正确识别一组同名的学生?
  • 当你说学生类时,每个将在该代码中开发的人都会认为这个类有学生列表。名字错了,我贴了答案

标签: c# .net


【解决方案1】:
var foundStudent = StudentsClassCollection.First(s => s.StudentName == "LookingForYou");
foundStudent.Passed = true;

【讨论】:

  • 当然,如果没有同名的学生,这将非常崩溃
  • @Steve 做了一些假设。当我确定我的数据时,我使用 First,无需怀疑并使用 FirstOrDefault。
【解决方案2】:

如果您通过索引知道哪个学生,那么很简单:

StudentsClassCollection[i].Passed = true

如果您要按姓名寻找学生,也许:

var student = StudentsClassCollection.FirstOrDefault(s => s.name == "Bob");
if (student != null) {
 student.Passed = true
}

为学生“鲍勃”

【讨论】:

  • 如果只有一个“Bob”,否则?
  • 如果有多个同名学生,那么系统就有更大的问题——你怎么知道哪个学生真正通过了?如果所有称为“Bob”的学生都必须通过的行为是有效的,您可以:foreach (var student in StudentsClassCollection.Where(s =&gt; s.name == "Bob") { student.passed = true; }
【解决方案3】:

oop 中最无能为力的事情之一是做基础的东西类应该被称为学生而不是学生(你可以在你的情况下看到它,当你希望它是你做的学生时学生)

    public List<Student> StudentsClassCollection = new List<Students>();
    StudentsClassCollection.Add(new Student("Ben","true"))

    public class Student
    {
        public string StudentName {get; set;}
        public bool Passed { get; set;}

        public Student(string name,Bool pass)
        {
           this.StudentName = name;
           this.Passed = pass;
        }
    }

    foreach(Student s in StudentsClassCollection)
    {
       if(s.StudentName.Equals("what you looking for"))
          s.Passed = true;
    }

【讨论】:

    【解决方案4】:

    使用 Linq 按姓名识别学生并将属性设置为 true。仅使用名称是查找记录的一种糟糕方式,因为您需要完全匹配(包括字母的大小写)。添加主键或将姓名拆分为第一个和最后一个,并包含出生日期。

        public void UpdateStudentToPassed(string studentName)
        {
           StudentsClassCollection.Single(obj => obj.StudentName == studentName).Passed = true;
        }
    

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-14
      相关资源
      最近更新 更多