我对逆变接口有疑问,不确定解决它的最佳方法。这些是我的课:
public interface IObject {
}
public interface IBigObject : IObject {
}
public interface ISmallObject : IObject {
}
public class AnObject : IBigObject {
}
public class DataWrapper<T> {
public T Data { get; set; }
}
我希望能够传递 a DataWrapper<IObject>
(可能是许多派生类)并将项目作为 a 获取,IObject
据我所知,我能做到这一点的唯一方法是这样的:
IObject itemToAdd = null;
if (values[1] is IObject) {
itemToAdd = values[1] as IObject;
} else if (values[1] is DataWrapper<IObject>) {
itemToAdd = ((DataWrapper<IObject>)values[1]).Data;
} else if (values[1] is DataWrapper<IBigObject>) {
itemToAdd = ((DataWrapper<IBigObject>)values[1]).Data;
} else if (values[1] is DataWrapper<BigObjectBase>) {
itemToAdd = ((DataWrapper<ObservableBigObject>)values[1]).Data;
} else if (values[1] is DataWrapper<ObservableBigObject>) {
itemToAdd = ((DataWrapper<ObservableBigObject>)values[1]).Data;
}
有没有更短的方法?