我试图这样做:
void someMethod(TypeA object) { ... }
void someMethod(TypeB object) { ... }
object getObject()
{
if (...) return new TypeA();
else return new TypeB();
}
object obj = getObject();
(obj.GetType()) obj; // won t compile
someMethod(obj);
显然,我在这里混淆不清。 我知道,我可以通过仅写有条件声明来完成这项工作。
if (obj.GetType() == typeof(TypeA)) obj = (TypeA)obj;
else if (obj.GetType() == typeof(TypeB)) obj = (TypeB)obj;
——但现在还未采取某种行动?
EDIT I agree it seems like perhaps not the best design choice, so here s the context. The point of the above code is Repository base class for Mongo DB. I want it to be able to handle different kinds of tables. So, someMethod() is actually remove; and TypeA and TypeB are ObjectID and Guid; the code at the bottom is part of a type-agnostic remove method that accepts the ID as a string; and getObject() is a method to parse the ID parameter.