我已经在 C# 中为 Windows 窗体应用程序初始化了一个 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);
现在,当我只想检查 ArrayList
中每个对象的 FieldName
时(假设 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?)
最佳答案
ArrayList
持有对象。它不是通用的并且类型安全。这就是为什么您需要强制转换对象以访问它的属性。而是考虑使用像 List<T>
这样的通用集合.
var FormFields = new List<CDatabaseField>();
CDatabaseField Db = new CDatabaseField();
...
FormFields.Add(Db);
然后您可以看到所有属性都将可见,因为现在编译器知道您的元素的类型并允许您以类型安全的方式访问您的类型的成员。
关于c# - 获取 ArrayList 中对象的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26612562/