浇注混凝土类通用基本接口 [英] Cast concrete class to generic base interface
问题描述
下面就是我面临的情况:
Here's the scenario i am faced with:
public abstract class Record { }
public abstract class TableRecord : Record { }
public abstract class LookupTableRecord : TableRecord { }
public sealed class UserRecord : LookupTableRecord { }
public abstract class DataAccessLayer<TRecord> : IDataAccessLayer<TRecord>
where TRecord : Record, new() { }
public abstract class TableDataAccessLayer<TTableRecord> : DataAccessLayer<TTableRecord>, ITableDataAccessLayer<TTableRecord>
where TTableRecord : TableRecord, new() { }
public abstract class LookupTableDataAccessLayer<TLookupTableRecord> : TableDataAccessLayer<TLookupTableRecord>, ILookupTableDataAccessLayer<TLookupTableRecord>
where TLookupTableRecord : LookupTableRecord, new() { }
public sealed class UserDataAccessLayer : LookupTableDataAccessLayer<UserRecord> { }
public interface IDataAccessLayer<TRecord>
where TRecord : Record { }
public interface ITableDataAccessLayer<TTableRecord> : IDataAccessLayer<TTableRecord>
where TTableRecord : TableRecord { }
public interface ILookupTableDataAccessLayer<TLookupTableRecord> : ITableDataAccessLayer<TLookupTableRecord>
where TLookupTableRecord : LookupTableRecord { }
现在,当我尝试做以下投,它不会编译:
Now, when i try to do the following cast, it does not compile:
UserDataAccessLayer udal = new UserDataAccessLayer();
ITableDataAccessLayer<TableRecord> itdal = (ITableDataAccessLayer<TableRecord>)udal;
然而,当我这样做投它没有运行时错误编译:
However, when i do the following cast it compiles with no runtime errors:
UserDataAccessLayer udal = new UserDataAccessLayer();
ITableDataAccessLayer<UserRecord> itdal = (ITableDataAccessLayer<UserRecord>)udal;
我真的需要与基础工作 ITableDataAccessLayer< TableRecord>
接口,因为我不知道具体类型。
I really need to work with the base ITableDataAccessLayer<TableRecord>
interface, as i don't know the concrete type.
希望这是描述性的,乐于助人的回答了我的问题。
Hope this is descriptive and helpfull enough to answer my question.
推荐答案
你所试图做的是支持.NET 4.0而不是3.5。这就是所谓的通用的协方差。你能做些什么,而不是在此期间,为创建一个名为ITableDataAccessLayer(使用Object类型,无论你会用T),并提供明确的接口实现非通用接口。这是多少泛型.NET处理它。
What you are trying to do is supported in .NET 4.0 but not 3.5. It's called generic covariance. What you can do instead in the meantime is create a non-generic interface called ITableDataAccessLayer (using type Object wherever you'd use T) and provide explicit interface implementation. This is how many generic types in .NET handle it.
这篇关于浇注混凝土类通用基本接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!