English 中文(简体)
如何将C#物体排入动态型
原标题:How to unbox a C# object to dynamic type

我试图这样做:

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.

最佳回答

如果您重新使用NET 4和C# 4,可为此使用dynamic:

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

否则,你不得不利用思考来寻找和援引正确的方法。 载重分辨率(非<条码>>动力学类型)在compile<>-time进行。

(请注意,除非<代码>TypeA和TypeB均为指示,否则,请在un Box<>m> 页: 1

问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...