使用IEnumerator进行类型转换的问题

本文关键字:问题 类型转换 IEnumerator 使用 | 更新日期: 2023-09-27 18:15:26

我不完全理解cast和序列化的所有复杂性,并且我在下面的代码中遇到了在第二个对象的GetEnumerator()代码块中生成cast错误的问题。

任何和所有的帮助都将非常感谢在解决这个问题,而且在更好地理解这一点。提前谢谢。

[Serializable]
public class DBFieldMap
{
    public String fieldName { get; set; }
    public String fieldValue { get; set; }
    public DBFieldMap() { }
    public DBFieldMap(String fname, String fvalue)
    {
        fieldName = fname;
        fieldValue = fvalue;
    }
    public IEnumerator GetEnumerator()
    {
        return (IEnumerator)this;
    }
}

第二个对象

[Serializable]
public class MappedSQLFields : Dictionary<String, DBFieldMap>
{
    public MappedSQLFields()
    {
        this.Add("clinicianstatus", new DBFieldMap());
        this.Add("researcherstatus", new DBFieldMap());
        this.Add("patientcarestatus", new DBFieldMap());
        this.Add("managerstatus", new DBFieldMap());
        this.Add("locationid", new DBFieldMap());
        this.Add("managerid", new DBFieldMap());

    }
    public IEnumerator GetEnumerator()
    {
        return (IEnumerator)this; ==>Error message  here is -Unable to cast object of type MappedSQLFields System.Collections.IEnumerator System.InvalidCastException
    }
    public MappedSQLFields(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
  }
主要对象:

public Audience()
{
...
    Dictionary<String, String> fields = new Dictionary<String, String>()
       {
        {"_locationid",""},
        {"_managerid",""},
        {"_clinicianstatus",""},
        {"_managerstatus",""},
        {"_patientcarestatus",""},
        {"_researcherstatus",""},
       };
    private void loadCriteria()
    { 
        //Load values into Dictionary
        foreach (KeyValuePair<String,DBFieldMap> item in audienceSQLMap) ==>Error in stack starts here
        {
            this.fields["_"+ item.Key] = item.Value.fieldValue; 
        }
    }
 }

使用IEnumerator进行类型转换的问题

DBFieldMap没有实现IEnumerable,所以我可以看到为什么强制转换会失败。

其次,MappedSQLFields 已经通过继承Dictionary<String, DBFieldMap>实现了IEnumerable<KeyValuePair<String, DBFieldMap>>,所以我不确定为什么你觉得你需要再次实现