将对象中的值从另一个类的属性中获取

时间:2017-03-08 14:55:00

标签: c# arrays object

我有一个gridview

INSEE1  Commune
------  -------
10002   AILLEVILLE
10003   BRUN

我有一个返回对象列表的脚本。

List<object> Temp = ASPxGridView_Insee.GetSelectedFieldValues("INSEE1");

我的Temp是我选择的INSSE1对象列表。

但现在我也添加了Commune,所以我的脚本变成了:

List<object> Temp = ASPxGridView_Insee.GetSelectedFieldValues("INSEE1","Commune");

和我的Temp是INSEE1的对象列表,Commune看图像:

enter image description here

我如何访问10002和AILLEVILLE?

我尝试使用我的Pers_INSEE类:

public class Pers_InseeZone
{
    string _Code_Insee;
    public string Code_Insee
    {
        get { return _Code_Insee; }
        set { _Code_Insee = value; }
    }

    string _Commune;
    public string Commune
    {
        get { return _Commune; }
        set { _Commune = value; }
    }
}

foreach (var oItem in Temp )
                {
Pers_InseeZone o = (Pers_InseeZone)oItem;

}

但我不工作,我不能施展它。 我试过这样的:

foreach (var oItem in Temp )
{
    var myTempArray = oItem as IEnumerable;

    foreach (var oItem2 in myTempArray)
    { 
        string res= oItem2.ToString();

...

res = 10002的值,但我怎样才能获得AILEVILLE的值?

Temp[0].GetType();的值是:

enter image description here

提前致谢

2 个答案:

答案 0 :(得分:1)

好的,我是这么认为的,正如评论中已经提到的,每个对象中都有一个对象数组,因此您需要先将列表中的每个对象转换为一个对象数组:object[]然后您就可以访问每个部分。以下是重新创建问题的示例:

object[] array = new object[] {10002, "AILEEVILLE"};    
List<object> Temp = new List<object> {array};

enter image description here

解决方案:

// cast here so that the compiler knows that it can be indexed
object [] obj_array = Temp[0] as object[];

List<Pers_InseeZone> persList = new List<Pers_InseeZone>();

Pers_InseeZone p = new Pers_InseeZone()
{
    Code_Insee = obj_array[0].ToString(),
    Commune = obj_array[1].ToString()
};

persList.Add(p);

应用于您的代码,它看起来像这样:

List<object> Temp = ASPxGridView_Insee.GetSelectedFieldValues("INSEE1","Commune");
List<Pers_InseeZone> persList = new List<Pers_InseeZone>();

foreach (object oItem in Temp )
{
    object [] obj_array = oItem as object[];

    Pers_InseeZone p = new Pers_InseeZone()
    {
        Code_Insee = obj_array[0].ToString(),
        Commune = obj_array[1].ToString()
    };

    persList.Add(p);
}

答案 1 :(得分:0)

问题在于,Pers_InseeZone与您获得的数据的结构不匹配,因此无法将其投入其中。

相反,为什么不直接对结果进行迭代并构建一个新的类实例?

button

您需要在setContentView类中添加构造函数,并在那里分配变量。