【发布时间】:2020-05-01 16:56:53
【问题描述】:
我有一个泛型类型,它基本上是另一个类的包装器(用于序列化目的)ChildFolder<SomeType>。
[Serializable]
public class ChildFolder<T>
{
public T value;
}
我有一个 ChildFolder 的引用,它当前的类型是 object。无论 T 是什么,我都需要能够访问该对象的 .value - 将其作为 object 是完美的。我希望泛型类型会遵循参数类的可遗传性规则,这样就可以了:
object obj = new ChildFolder<SomeClass>(); // (this is equivalent to what's coming in to the function as a parameter)
ChildFolder<object> chObj = (ChildFolder<object>)obj;
// and now chObj.value is of type object
但是这条线给了我InvalidCastException: Specified cast is not valid.
如果我不知道<T> 是什么,我该如何转换为 ChildFolder?或者,如何在不进行类型转换的情况下访问 .value?
【问题讨论】: