【问题标题】:how to call the generic method IEnumerator<> IEnumerable<>.GetEnumerator()?如何调用泛型方法 IEnumerator<> IEnumerable<>.GetEnumerator()?
【发布时间】:2015-05-19 09:14:17
【问题描述】:

对于某些调试,我需要获取由 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;
    }
}

【问题讨论】:

    标签: c#


    【解决方案1】:

    要完全按照您的要求进行操作,您需要将 oAttributiDocumentoList 转换为 (IEnumerable&lt;SqlDataRecord&gt;),如下所示:

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

    但是使用Enumerators 有一些缺点。

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

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

    如果您仍然喜欢坚持使用.GetEnumerator();,请不要忘记将其丢弃或拥抱using。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 2020-01-18
    • 1970-01-01
    相关资源
    最近更新 更多