简体   繁体   English

使用get类型然后在C#中转换为该类型

[英]Using get type and then casting to that type in C#

I have code like: 我的代码如下:

var t = SomeInstanceOfSomeClass.GetType();
((t)SomeOtherObjectIWantToCast).someMethodInSomeClass(...);

That won't do, the compiler returns an error about the (t) saying Type or namespace expected. 那不行,编译器返回关于(t)说预期的Type或名称空间的错误。 How can you do this? 你怎么能这样做?

I'm sure it's actually really obvious.... 我相信它确实很明显......

C# 4.0 allows this with the dynamic type. C#4.0允许使用dynamic类型。

That said, you almost surely don't want to do that unless you're doing COM interop or writing a runtime for a dynamic language. 也就是说, 除非您正在进行COM互操作或为动态语言编写运行时, 否则几乎肯定不希望这样做。 (Jon do you have further use cases?) (Jon你还有其他用例吗?)

I've answered a duplicate question here . 我在这里回答了一个重复的问题。 However, if you just need to call a method on an instance of an arbitrary object in C# 3.0 and below, you can use reflection: 但是,如果您只需要在C#3.0及更低版本的任意对象的实例上调用方法,则可以使用反射:

obj.GetType().GetMethod("someMethodInSomeClass").Invoke(obj);
if(t is ThisType) {
    ThisType tt = (ThisType)t;
    /*do something here*/
}else if(t is ThatType) {
    ThatType tt = (ThatType)t;
    /*do something here*/
}

etc. 等等

That's the best you can do in C# 3.5 and lower, really. 这是你在C#3.5及更低版本中所做的最好的,真的。

In order to cast the way you're describing in your question you have to declare the type at compile time, not run time. 为了在你的问题中转换你描述的方式,你必须在编译时声明类型,而不是运行时。 That is why you're running into problems. 这就是你遇到问题的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM