如何拆箱一个C#对象动态类型对象、类型、动态

2023-09-03 04:51:18 作者:孤妄

我试图做这样的事情:

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?

修改 我同意这似乎是也许不是最好的设计选择,所以这里的环境。上述code点是蒙戈DB信息库基类。我希望它能够处理各种不同的表。因此,的someMethod()实际上的删除的;和类型A和类型B是的对象ID 和的Guid 的;在code在底部的一部分,一种不可知的删除的方法,该方法接受ID作为一个字符串;和getObject()是一个方法来解析的ID参数。

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.

推荐答案

如果您使用的是.NET 4和C#4,您可以使用动态此:

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

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

否则,你将不得不使用反射来查找和调用正确的方法。重载(非 - 动态类型)。在被执行的编译的-time

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.

(注意,除非类型A 的TypeB 的结构,你会不会的拆箱反正...)

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