[英]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.... 我相信它确实很明显......
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.