我有一个我必须使用的设计糟糕的第 3 方库。
它有各种各样的类型,我们称它们为SomeType1、SomeType2等
。这些类型都不共享一个公共基类,但都有一个名为 Value 的属性,具有不同的返回类型。
我想要做的就是能够 Mixin 这个类,这样我就可以调用someType1Instance.Value
并且someType2Instance.Value
不关心它是什么 concreate 类型,也不关心返回类型是什么(我可以使用object
)。
所以我的代码目前是:
public interface ISomeType<V>
{
V Value {get; set;}
}
public interface ISomeTypeWrapper
{
object Value { get; set; }
}
public class SomeTypeWrapper<T> : ISomeTypeWrapper
where T : ISomeType<???>
{
T someType;
public SomeTypeWrapper(T wrappedSomeType)
{
someType = wrappedSomeType
}
public object Value
{
get { return someType.Value; }
set { someType.Value = value != null ? value : default(T); }
}
}
public class SomeType1
{
public int Value { get; set; }
}
public class SomeType2
{
public string Value { get; set; }
}
问题是我直到运行时才知道 T 可能是什么,因为我得到了一个对象字典。
我可以迭代字典并使用反射在运行时创建 SomeWrapperType 但我想避免它。
如何将 SomeType 的 concreate 类型混合到 ISomeType?
我怎么知道V型参数是什么?(希望我有像 C++ 中的 typedef 和 decltype)
我怎样才能尽可能少地使用反射将这些类与接口/基类混合?