【问题标题】:How do I add values to the list of a class type c which in turn contains 2 other classes objects?如何将值添加到类类型 c 的列表中,该列表又包含 2 个其他类对象?
【发布时间】:2020-01-22 10:15:45
【问题描述】:
Public class A 
{
    public string str1;
    public string str2;
}

Public class B {

    public string str3;
}

Public class C 
{
    B BclassObject;

    //here is a getter; setter to get and set BClassObject;

    A AclassObject;

    //here is a getter; setter to get and set AClassObject;


}

现在我从数据库返回数据,其中包含数据表中的列 str1、str2 和 str3,例如dt.

public List<C> someFunc()
{     

     List<C> listC= new List<C>();

     for(int i=0; i<dt.rows.count; i++)
     {
         C ClassObject = new C();
         listC.Add(new C(){});         
     } 

         return listC;
}

现在这是最后一个函数的问题。我想将值分配给AB 类中的str1str2str3

我该怎么做?

【问题讨论】:

  • ClassObject.AclassObject.str1 = ... 然后listC.Add(ClassObject);
  • 根据需要将AclassObject和BclassObject的可见性设置为public或internal,以便可以从someFunc中看到它们

标签: c# asp.net .net oop c#-4.0


【解决方案1】:

您可以在C类中添加一个构造函数,接受str1str2str3,然后使用这些参数创建A类和B类的对象。

Public class A 
{
  public string str1;
  public string str2;
}

Public class B {
 public string str3;
}

Public class C 
{
 B BclassObject;
//here is a getter; setter to get and set BClassObject;
 A AclassObject;
//here is a getter; setter to get and set AClassObject;
 public C(string v1, string v2, string v3){
  AclassObject = new A() {str1=v1,str2=v2};
  BclassObject = new B(){str3 = v3};
 }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-05
    • 2011-09-24
    • 1970-01-01
    • 2019-07-01
    • 2023-04-03
    • 2015-04-25
    • 1970-01-01
    相关资源
    最近更新 更多