3

我对逆变接口有疑问,不确定解决它的最佳方法。这些是我的课:

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;
} 

有没有更短的方法?

4

1 回答 1

5

类在 C# 中不能有差异,因此您必须创建一个接口,例如

public interface IObjectWrapper<out T> where T : IObject
{
    T Value { get; }
}

那么你应该能够做到

if(values[1] is IObjectWrapper<IObject>)
{
    itemToAdd = ((IObjectWrapper<IObject>)values[1]).Value;
}

如果你不想这样做,你可以使用反射:

Type t = values[1].GetType();
if(t.IsGenericType && 
    t.GetGenericTypeDefinition() == typeof(DataWrapper<>) && 
    typeof(IObject).IsAssignableFrom(t.GetGenericArguments()[0]))
{
    itemToAdd = (IObject)t.GetProperty("Data").GetValue(value[0], null)
}
于 2013-05-26T12:12:32.247 回答