【发布时间】:2012-01-27 04:20:16
【问题描述】:
这应该可以使用 c# 4 和 VS 2010 实现吗?我正在对实现通用接口的类进行一些处理,处理后希望将对象转换为更简单的接口,以便提取通用接口定义的某些属性。
interface IMyInterface
{
public Id { get; set; }
}
interface IFile<T1, T2> where T1 : IMyInterface where T2 : IMyInterface
{
Int64 prop1 { get; set; }
T1 t1 { get; set; }
T2 t2 { get; set; }
}
ClassA : IMyInterface
{
... Implement some properties plus interface
public Id { get; set; }
}
ClassB : IMyInterface
{
... Implement some properties plus interface
public Id { get; set; }
}
例如,这个类有 ClassX 和 ClassY,我希望它们成为某些类型以进行处理/保存,但之后我只想提取公共属性,如 ID,这在实现此通用接口的所有类中很常见(其他属性在t1,t1中不常见)
ClassSomething : IFile<ClassA, ClassB>
{
... Implement properties plus interface
public ClassX t1
{ get {} set {} }
public ClassY t2
{ get {} set {} }
}
IList<IFile<TItem1, TItem2>> list = new List<IFile<TItem1, TItem2>>()
ClassA ca = new ClassA();
... Fill in the interface defined properties
... Fill the list with objects of ClassSomething
foreach (IFile<TItem1, TItem2> x in list)
{
// This fails
IFile<IMyInterface, IMyInterface> interfaceItem =
(IFile<IMyInterface, IMyInterface>)x;
}
将上面的x(特别是t1 和t2 属性)转换为更简单的IMyInterface 接口失败。
有很多通用界面问题,但我没有看到(或认识?)任何解决方案。
【问题讨论】:
-
你可能需要看看c# 4.0 covariance and contravariance
-
哇,答案又快又好看。我需要花一点时间消化答案。 :)
-
很好的答案,他们都很有帮助,我会根据大众投票选择一个答案。 (我