0

我收到一个编译错误,“无法将类型'System.Collections.ObjectModel.ObservableCollection'隐式转换为ProddataRecsObservable'。存在显式转换”请参阅以下代码段中的注释。

//I created a custom class called ProddataRecsObservable derived from
//ObservableCollection<Proddata> so I can do some special CRUD operations for my production
//data records.

public class ProddataRecsObservable : ObservableCollection<Proddata>
{

}        

//I have another class which maps an object to a reader and the function MappAll returns an 
//Observable collection of type <T>.

public abstract class MapperBase<T>
{
    protected abstract T Map(IDataRecord record);

    public ObservableCollection<T> Mapall(IDataReader reader)
    {
        ObservableCollection<T> collection = new ObservableCollection<T>();

        while (reader.Read())
        {
            try
            {
                collection.Add(Map(reader));
            }
            catch
            {
                throw;
            }
        }

        return collection;
    }
}

//I have another class derived from MapperBase called ProddataMapper.

public class ProddataMapper : WTS.Data.Mapper.MapperBase<Proddata>
{
    protected override Proddata Map(System.Data.IDataRecord record)
    {
        Proddata p = new Proddata();    

        p.PSTAT = (DBNull.Value == record["PSTAT"]) ? "" : record["PSTAT"].ToString();

 return p;
    }
}

//In my calling code, I attempt to set a ProddataRecsObservable variable equal to the 
//result of MapAll() from my ProddataMapper class but get the compile error. The error even 
//tells me they are the same type which is strange. How can I get around this?

//Calling Code:

ProddataMapper prodMapper = new ProddataMapper(); 
ProddataRecsObservable recs = prodMapper.Mapall(ProddataReader); //ERROR'S HERE <-
4

4 回答 4

6

我没有看到它告诉你类型是相同的。ProddataRecsObservable不是一回事ObservableCollection<Proddata>-是什么让您认为它们是同一类型?第一种类型派生自第二种类型 - 这不会使它们成为相同的类型。

由于继承关系,每个实例ProddataRecsObservable都是一个实例ObservableCollection<Proddata>,但反之则不然。

你在做什么相当于:

class Test : object {}

object Foo()
{
    return new object();
}
...
Test t = Foo();

你会期望这行得通吗?如果是这样,您为什么希望它起作用?编译器如何知道它实际上Foo会返回一个实例(实际上它不在这里 - 您的方法也不返回派生类的实例)?如果您希望它起作用,为什么您希望您的示例代码起作用?Test

于 2009-10-13T14:32:46.867 回答
1

ObservableCollection<Proddata>不能向上转换为,其中还有不知道的ProddataRecsObservable附加逻辑。ProddataRecsObservableObservableCollection<Prodddata>

于 2009-10-13T14:35:38.353 回答
0

在基类中使 MapAll() 抽象,然后在 ProdDataMapper 中提供覆盖:

public override ProddataRecsObservable Mapall(IDataReader reader)
{
   // do the downcast explicitly
    return (ProddataRecsObservable) base.MapAll(reader);
}
于 2009-10-13T15:02:00.957 回答
0

约翰斯基特是对的。尝试在出现错误的分配中将结果显式转换为 ProddataRecsObservable。

于 2009-10-13T15:06:01.933 回答