我收到编译错误,“无法隐式转换类型'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 <-
答案 0 :(得分:6)
我没有看到它告诉你类型完全相同。 ProddataRecsObservable
与ObservableCollection<Proddata>
不同 - 是什么让你认为它们属于同一类型?第一种类型派生自第二种类型 - 它不会使它们成为相同的类型。
由于继承关系,ProddataRecsObservable
的每个实例都是ObservableCollection<Proddata>
的实例,但反之则不然。
你在做什么相当于:
class Test : object {}
object Foo()
{
return new object();
}
...
Test t = Foo();
你希望它能起作用吗?如果是这样,你为什么期望它起作用?编译器如何知道Foo
将实际返回Test
的实例(实际上它不在此处 - 您的方法也不会返回您的实例衍生类)?如果您不希望希望它能够正常工作,那么为什么您希望您的示例代码能够正常工作?
答案 1 :(得分:1)
ObservableCollection<Proddata>
无法升级到ProddataRecsObservable
,ProddataRecsObservable
中ObservableCollection<Prodddata>
还有其他逻辑{{1}}不知道。
答案 2 :(得分:0)
在基类中创建MapAll()抽象,然后在ProdDataMapper中提供覆盖:
public override ProddataRecsObservable Mapall(IDataReader reader)
{
// do the downcast explicitly
return (ProddataRecsObservable) base.MapAll(reader);
}
答案 3 :(得分:0)
John Skeet是对的。尝试在得到错误的分配中将结果显式地转换为ProddataRecsObservable。