English 中文(简体)
1. 使用时间类型和投射回物体的通用方法
原标题:Call Generic method using runtime type and cast return object
  • 时间:2010-12-31 13:49:33
  •  标签:
  • c#
  • generics

I m 采用反射方法,用一种在操作时间确定的通用方法。 我的法典如下:

Type tType = Type.GetType(pLoadOut.Type);
MethodInfo method = typeof(ApiSerialiseHelper).GetMethod("Deserialise", new Type[] { typeof(string) });
MethodInfo generic = method.MakeGenericMethod(tType);
generic.Invoke(obj, new object[] { pLoadOut.Data });

.。 然而,一般而言。 Invoke方法将物体退回,但我喜欢的是操作时间确定的类型。 这种做法是否可行,或者是否有更好的选择?

标记

最佳回答

运行时间确定的各类IS。 参照变量的类型是标的,实际的类型是严格分类的。

考虑到你重新利用思考,积极获取汇编者没有哪类信息的方法——在建筑环境中甚至可能不存在这种信息——这是最好的。

EDIT:如果你知道通过<代码>脱硫/代码”归还的类型,那么你就可以利用代表的差异。 例如:

Type tType = Type.GetType(pLoadOut.Type);
MethodInfo method = typeof(ApiSerialiseHelper).GetMethod("Deserialise", new Type[] { typeof(string) });
MethodInfo generic = method.MakeGenericMethod(tType);
Converter<string,ISomething> deser = (Converter<string,ISomething>)Delegate.CreateDelegate(typeof(Converter<string,ISomething>),generic);
ISomething result = deser(pLoadOut.Data);
问题回答

如果返回的物体具有共同的祖先或界面,那么你可以投给它们。 如果他们不这样做,那么他们就应当,例如,如果所有可能的返回类型都有一种称为DoSomething()的方法,那么就能够形成一种具有“DoSomething()”方法的接口。





相关问题
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. ...

热门标签