C#从集合类访问对象的属性

时间:2009-06-10 17:54:15

标签: c# vb.net

我正从VB转到C#。我试图循环一个集合类,这是一个数据类的集合,但我似乎无法从数据类属性中获取实际值(找到正确的代码来执行此操作)。我有一个循环通过集合类(Contacts)并保存每个记录(Contact)的方法。我正在使用反射,因为我的方法不知道它是Contacts类还是Customer类等等。这是我在VB中的代码(淡化)

Public Function SaveCollection(ByVal objCollection as Object, ByVal TableName as string, ByVal spSave as string)

 Dim objClass as Object
 Dim propInfo as PropertyInfo

For Each objClass in objCollection

    propInfo = objClass.GetType.GetProperty("TableFieldName")


Next

End Function

我在使用objClass.GetType.GetProperty(“TableFieldName”)行的C#中遇到问题

这是我的C#代码

public in SaveCollection(DictionaryBase objCollection, string TableName, string spSave)
{
    PropertyInfo propInfo;

   foreach (DictionaryEntry objClass in objCollection)
      {
       propInfo = objClass.GetType().GetProperty("TableFieldName")

       }

}

C#代码保持返回null。在我的本地窗口中,我可以看到objClass上的类的属性和属性的值,但我似乎可以弄清楚如何通过代码访问它。我使用了DictionaryBase,因为这似乎与我需要做的非常匹配。我的数据类(Contact)有一堆或多个属性,与联系表数据库中的字段名称相匹配。获得propInfo变量集后,然后使用fieldname,datatype等设置我的SQLParameter,然后将值设置为propInfo.value。

感谢您的帮助。

5 个答案:

答案 0 :(得分:3)

看起来您正在将不同的集合传递给VB代码和C#代码。我的猜测是,在VB代码中,您传递的是字典的值,而在C#中,您传递的是字典本身。尝试将C#行更改为以下

propInfo = objClass.Value.GetType().GetProperty("TableFieldName");

答案 1 :(得分:2)

我不明白为什么你在这里使用字典 - 如果它只是一个集合,为什么不是IEnumerable?你实际上在这里有一个关键,你要存放东西吗?

DictionaryEntry永远不会有TableFieldName属性。您确定不需要在DictionaryEntry中使用(或键)(使用ValueKey属性)。

你真的需要用反射来做这件事吗?在定义具有TableFieldName属性的公共接口后,是否可以使用泛型方法?例如:

public void SaveCollection<T>(IEnumerable<T> collection)
    where T : ITableDescriptor
{
    foreach (T element in collection)
    {
        string tableFieldName = element.TableFieldName;
        // use the table field name here
    }
}

答案 2 :(得分:1)

你需要获得后面的值。另请注意,GetValue返回object,然后您可以将其转换为字符串或整数或您期望值的任何类型。

public in SaveCollection(DictionaryBase objCollection, string TableName, string spSave)
{
    PropertyInfo propInfo;

   foreach (DictionaryEntry objClass in objCollection)
      {
           object tempObj = objClass.Value;
           propInfo = tempObj.GetType().GetProperty("TableFieldName");

           object[] obRetVal = new Object[0];
           object value = propInfo.GetValue(tempObj,obRetVal);
       }

}

如果你知道TableFieldName将是一个字符串,那么改变这一行。

string value = propInfo.GetValue(tempObj,obRetVal) as string;

答案 3 :(得分:0)

您正在查看DictionaryEntry类的属性。不是特定键值对中的值的类。请考虑尝试使用objClass.Value.GetType().GetProperty("TableFieldName")

答案 4 :(得分:0)

如果可以,还可以考虑切换到泛型。我认为你应该可以这样做:

VB:

Private l As List(Of MyClassName)

C#:

private List<MyClassName> l;

您可能不想使用列表,但这只是一个示例。之后,可以通过智能感知来访问列表中每个项目的成员。通常,仿制药也可以更快,因为您不需要进行任何铸造。

相关问题