【问题标题】:Access classes property of Class property访问 Class 属性的 classes 属性
【发布时间】:2013-11-13 19:04:42
【问题描述】:

代码:

 public class ClassA
 {
      public decimal foo
 }

 public class ClassB
 {
   public List<ClassA> Alist 
 }

在 ClassB 中,我像这样向 Alist 填充值。

      foreach (junk in trash)
        {              
            Alist.add(new ClassA()
            {                   
                foo = junk.Bar
            });     
          // if (Alist.foo == whatever)
          // but  no access to Alist.foo here 
        }

在 for each 循环中,我尝试对 foo 运行 if 语句。 所以像if (Alist.foo == whatever) 我不能这样做,它不允许我访问Alist.foo。任何想法如何做到这一点。

【问题讨论】:

  • 您的语法,如图所示,无法编译。尝试发布真正的代码,或者至少是可以工作的代码......
  • 是的,我遗漏了一些东西,但这是我的问题的总体思路。我必须使用 for 循环吗?如果是这样的话,我应该能够做我想做的事
  • 很难说,但您可能正在寻找索引器,如Alist[0].foo,但由于代码不完整,我不确定。
  • Alist.add(new Alist()....你的意思是new ClassA吗?
  • 是的,看来我可以用junk.foo做我想做的事

标签: c# if-statement properties foreach


【解决方案1】:

问题是您没有对刚刚添加的对象的引用。有很多方法可以得到这个。我将建议您简单地在 Add 之外构建对象。

var newA = new ClassA()
{                   
    foo = junk.Bar
};

// now you can perform the if statement
if (newA.foo == someValue)
{
    // do something
}

Alist.add(newA);

【讨论】:

  • 我可以在我的 foreach 中使用 junk.foo 获得访问权限,您对此有何看法?
  • @CSharper,您是说只访问junk 上的decimal 值而不是if 语句?是的,这是另一种可能的方法。
  • 是的,这就是我需要的,我想我会访问它有一个描述,应该不是问题
  • @CSharper,很高兴能为您提供帮助。
猜你喜欢
  • 2019-07-05
  • 2017-02-12
  • 2016-02-13
  • 2012-12-07
  • 2015-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多