为什么我会收到以下代码的类型转换编译错误?
我的项目中有很多派生 Def/View 类的实例。它们都有一些代码库,比如持久性、检索等。我认为通过使用泛型编写一个辅助类,我可以实现这个通用代码库的可维护性。
但是,我在将视图分配给 def 的行的 DoSomeStuff 方法中出现“类型转换”编译错误。我已经为所有基类和派生类编写了隐式强制转换。
请注意,Def & View 类故意不派生自某个公共类。此外,我总是只想从 View 转换为 Def,而不是反过来,因此只有我的 View 类在它们上定义了隐式转换。
我确实尝试关注 Eric Lipert 关于协变和逆变的讨论,但随着他的示例的推进,我的脑海中变得非常混乱。非常感谢您对此问题的任何帮助。
public class BaseDef
{
public int Id { get; set; }
}
public class DerivedDef : BaseDef
{
public string Name { get; set; }
public DerivedDef()
: base()
{
}
public DerivedDef(BaseDef bd)
{
this.Id = bd.Id;
}
}
public class BaseView
{
public int Id { get; set; }
public BaseView()
{
}
public BaseView(BaseDef bd)
{
Id = bd.Id;
}
public BaseDef ToBaseDef()
{
return new BaseDef { Id = this.Id };
}
public static implicit operator BaseView(BaseDef bd)
{
return new BaseView(bd);
}
public static implicit operator BaseDef(BaseView bv)
{
return bv.ToBaseDef();
}
}
public class DerivedView : BaseView
{
public string Name { get; set; }
public DerivedView()
: base()
{
}
public DerivedView(DerivedDef dd)
: base(dd)
{
Name = this.Name;
}
public DerivedDef ToDerivedDef()
{
return new DerivedDef(this)
{
Name = this.Name,
};
}
}
public class SomeHelper<Tdef, Tview>
where Tdef : BaseDef
where Tview : BaseView
{
public void DoSomeStuff(Tview vm)
{
Tdef df = vm; // this line give a compile error 'Cannot convert type 'Tview' to 'Tdef'
// work with df from here on
}
}