How to unbox a C# object to dynamic type

你。 提交于 2019-12-19 14:26:09

问题


I'm trying to do something like this:

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);

Obviously I'm confused here. I know I could make this work by just writing out a conditional statement --

if (obj.GetType() == typeof(TypeA)) obj = (TypeA)obj;
else if (obj.GetType() == typeof(TypeB)) obj = (TypeB)obj;

-- but isn't there some way to do this at runtime?

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.


回答1:


If you're using .NET 4 and C# 4, you can use dynamic for this:

dynamic obj = GetObject();
SomeMethod(obj);

Otherwise, you'll have to use reflection to find and invoke the right method. Overload resolution (for non-dynamic types) is performed at compile-time.

(Note that unless TypeA and TypeB are structs, you wouldn't be unboxing anyway...)



来源:https://stackoverflow.com/questions/10094067/how-to-unbox-a-c-sharp-object-to-dynamic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!