2014-10-28 10 views
2

我已经在C#中为windows窗体应用程序初始化了一个ArrayList。我加入与在ArrayList每个对象的一些属性,如新的对象:在ArrayList中获取对象属性的值

ArrayList FormFields = new ArrayList(); 

CDatabaseField Db = new CDatabaseField(); 
Db.FieldName = FieldName; //FieldName is the input value fetched from the Windows Form 
Db.PageNo = PageNo; //PageNo, Description, ButtonCommand are also fetched like FieldName 
Db.Description = Description; 
Db.ButtonCommand = ButtonCommand; 
FormFields.Add(Db); 

现在,当我想只检查每个对象的FieldNameArrayList(假设有在ArrayList许多对象) 。我怎样才能做到这一点??

我尝试:

for(int i=0; i<FormFields.Count; i++) 
{ 
    FieldName = FormFields[i].FieldName; 
} 

但这产生错误(在IDE)。我是C#编程的新手,所以有人可以帮助我解决这个问题?

Error: Error 21 'object' does not contain a definition for 'FieldName' and no extension method 'FieldName' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

+1

您可以用'CDatabaseField'而不是数组列表清单? – 2014-10-28 15:45:45

+0

'Recipe'' OP's'最好的办法是实际创建一个CDatabaseField列表,就像'Selman22'指出的那样.'List ' – MethodMan 2014-10-28 15:50:59

+0

Daniel,实际上我正在研究一个旧软件,它实现了一个名为arraylist的命名FormFields存储CDatabaseField的列表,它正在软件中的千位使用。要将数组列表更改为列表,我需要在很多地方改变它,现在不可行。 你可以建议我一种方法来获取从arraylist中的对象的特定字段名? – 2014-10-28 16:23:51

回答

2

终于想出了答案。 我试着投的对象为保存在ArrayList中的每个对象并最终可以提取每个对象的必填字段:

for (int i = 0; i < FormFields.Count; i++) 
{ 
    CDatabaseField Db = (CDatabaseField)FormFields[i]; 
    Label1.Text = Db.FieldName; //FieldName is the required property to fetch 
} 
4

ArrayList保持对象。它不是通用的,并且类型安全。这就是为什么你需要投射你的对象来访问它的属性。请考虑使用通用集合,如List<T>

var FormFields = new List<CDatabaseField>(); 
CDatabaseField Db = new CDatabaseField(); 
... 
FormFields.Add(Db); 

然后,你可以看到,因为现在编译器知道你的元素的类型,并允许您访问类型的成员类型安全方式的所有属性将是可见的。

+0

我现在试过这个方法,但'var'在Visual basic中产生一个错误:Error 无法找到类型或名称空间名称'var'(缺少using指令还是程序集引用?) – 2014-10-28 16:16:34

+0

Selman22 ,实际上我正在研究一个旧软件,它实现了一个名为FormFields的数组列表来存储CDatabaseField的列表,该列表正在软件中的数千个地方使用。要将数组列表更改为列表,我需要在很多地方改变它,现在不可行。你可以建议我从列表中的对象中获取特定字段名吗? – 2014-10-28 16:28:12

1

正如已经指出的,并根据this

The Item returns an Object , so you may need to cast the returned value to the original type in order to manipulate it. It is important to note that ArrayList is not a strongly-typed collection. For a strongly-typed alternative, see List<T> .

但是作为另一种选择是使用foreach循环代替for。当foreach运行时,它会尝试的ArrayListcast元素CDatabaseField,如果一个元素是不能转换到CDatabaseField你会得到一个InvalidCastException

foreach (CDatabaseField item in FormFields) 
{ 
    FieldName = item.FieldName; 
} 

根据foreachdocumentation和C#6语法上面的代码就相当于为此:

var enumerator = FormFields.GetEnumerator(); 
try 
{ 
    while (enumerator.MoveNext()) 
    { 
     CDatabaseField item = (CDatabaseField)enumerator.Current; 
    } 
} 
finally 
{ 
    var disposable = enumerator as IDisposable; 
    disposable?.Dispose(); 
}