要把Object 轉成它的真正型別 (ex: GoodBaseStep type),可以有下列 5 種方式:
** 如果知道它的真正型別 -
// explicit cast: if failed, throw 'InvalidCastException'
var goodStep = (GoodBaseStep)obj;
goodStep.HelloFunction();
// as operator: if failed, return null
var goodStep = obj as GoodBaseStep;
goodStep.HelloFunction();
** 如果不知道它的真正型別 -
例如:
// interface
IBaseStep step = (IBaseStep)obj;
step.HelloFunction();
// dynamic: represents an object whose operations will be resolved at runtime
dynamic step= obj;
step.HelloFunction();
** 如果知道它的真正型別 -
// explicit cast: if failed, throw 'InvalidCastException'
var goodStep = (GoodBaseStep)obj;
goodStep.HelloFunction();
// as operator: if failed, return null
var goodStep = obj as GoodBaseStep;
goodStep.HelloFunction();
** 如果不知道它的真正型別 -
- reflection
- implementing a well-known interface
- dynamic
例如:
// reflection
obj.GetType().GetMethod("HelloFunction").Invoke(obj, null);
// interface
IBaseStep step = (IBaseStep)obj;
step.HelloFunction();
// dynamic: represents an object whose operations will be resolved at runtime
dynamic step= obj;
step.HelloFunction();
沒有留言:
張貼留言