如何投放对象的实际类型? [英] How to cast Object to its actual type?
本文介绍了如何投放对象的实际类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有:
void MyMethod(Object obj) { ... }
我怎么能投 OBJ
其实际类型是什么?
推荐答案
如果您知道实际的类型,然后只是:
If you know the actual type, then just:
SomeType typed = (SomeType)obj;
typed.MyFunction();
如果你不知道实际的类型,那么:不是真的,没有。你将不得不改用之一:
If you don't know the actual type, then: not really, no. You would have to instead use one of:
- 反射
- 实施一个众所周知的接口
- 动态
例如:
// reflection
obj.GetType().GetMethod("MyFunction").Invoke(obj, null);
// interface
IFoo foo = (IFoo)obj; // where SomeType : IFoo and IFoo declares MyFunction
foo.MyFunction();
// dynamic
dynamic d = obj;
d.MyFunction();
这篇关于如何投放对象的实际类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文