如何调用泛型方法IEnumerator<> IEnumerable的<> .GetEnumerator()?

时间:2015-05-19 09:14:17

标签: c#

对于某些调试,我需要获取由TVPDataCollection类的IEnumerator IEnumerable.GetEnumerator()方法生成的SqlDataRecord列表

此代码:

TVPDataCollection<AttributiDocumento> oAttributiDocumentoList = new  TVPDataCollection<AttributiDocumento>();

        AttributiDocumento doc1 = new AttributiDocumento();
        AttributiDocumento doc2 = new AttributiDocumento();

        oAttributiDocumentoList.Add(doc1);
        oAttributiDocumentoList.Add(doc2);

        var x = oAttributiDocumentoList.GetEnumerator();

x是AttributiDocumento的列表,但我需要一个SqlDataRecord列表,因为我想检查这些值。什么是调用返回SqlDataRecord的GetEnumerator()的方法?

public class TVPDataCollection<T> : List<T>, IEnumerable<SqlDataRecord> where T : class
{
    IEnumerator<SqlDataRecord> IEnumerable<SqlDataRecord>.GetEnumerator()
    {
        List<SqlMetaData> records = new List<SqlMetaData>();
        var properties = typeof(T).GetProperties();
        foreach (var prop in properties)
        {
            SqlType oSqlType = GetSqlType(prop);
            if (oSqlType.UseSize)
                records.Add(new SqlMetaData(prop.Name, oSqlType.SqlDbType, oSqlType.Size));
            else
                records.Add(new SqlMetaData(prop.Name, oSqlType.SqlDbType));


        }

        SqlDataRecord oSqlDataRecord = new SqlDataRecord(records.ToArray());

        foreach (T data in this)
        {
            for (int i = 0; i < properties.Length; i++)
            {
                oSqlDataRecord.SetValue(i, properties[i].GetValue(data, null));

            }
            yield return oSqlDataRecord;
        }
    }
}
public class AttributiDocumento
{
    public int IdProvPart { get; set; }

    //uso stringa in quanto con data agigunge 2 ore del fuso orario

    public DateTime Data { get; set; }

    public int Articolo { get; set; }

    public int ExArticolo { get; set; }

    public int DocVer { get; set; }

    [LenAttribute(255)]
    public string Altro { get; set; }

    public AttributiDocumento()
    {
        this.Data = new DateTime(1900, 1, 1);
        this.Altro = string.Empty;
    }
}

1 个答案:

答案 0 :(得分:2)

要完全满足您的要求,您需要将oAttributiDocumentoList投射到(IEnumerable<SqlDataRecord>),如下所示:

var x = ((IEnumerable<SqlDataRecord>)oAttributiDocumentoList).GetEnumerator();

但使用Enumerators时存在一些缺点。

通常您需要访问可枚举的元素。为此,只需使用foreach循环。

foreach(var record in ((IEnumerable<SqlDataRecord>)oAttributiDocumentoList)) {
        //Do whatever you want with        record    
    }

如果您仍然愿意坚持使用.GetEnumerator();,请不要忘记最后处理它或拥抱using