简体   繁体   English

确定对象的投射

[英]Determining casting of an object

I have the code below 我有下面的代码

RssFeedReader rss = (RssFeedReader)this.ParentToolPane.SelectedWebPart;

My problem is only at run time do I know if 'this.ParentToolPane.SelectedWebPart' is of type RssFeedReader or of type 'RssCountry' 我的问题是仅在运行时知道'this.ParentToolPane.SelectedWebPart'是RssFeedReader类型还是'RssCountry'类型

How would I check the object type and cast it appropriatley? 我将如何检查对象类型并将其强制转换为?

Many Thanks, 非常感谢,

You can do this: 你可以这样做:

if (this.ParentToolPane.SelectedWebPart is RssFeedReader)
    //...

To check if it is of a certain type. 检查它是否是某种类型。 Alternatively, you can use 'as' to use it as a type, and it will be null if it was not of that type. 另外,您可以使用“ as”将其用作类型,如果不是该类型,则它将为null。

RssFeedReader reader = this.ParentToolPane.SelectedWebPart as RssFeedReader;
if (reader != null)
{
    //...
}

You could say 你可以说

RssFeedReader rss;
rss = this.ParentToolPane.SelectedWebPart as RssFeedReader;
if(rss != null) {
    // an RssFeedReader
}

RssCountry rc;
rc = this.ParentToolPane.SelectedWebPart as RssCountry;
if(rc != null) {
    // an RssCountry
}

or 要么

if(this.ParentToolPane.SelectedWebPart is RssFeedReader) {
    // an RssFeedReader
    RssFeedReader rss = (RssFeedReader)this.ParentToolPane.SelectedWebPart;
}

if(this.ParentToolPane.SelectedWebPart is RssCountry) {
    // an RssCountry
    RssCountry rc = (RssCountry)this.ParentToolPane.SelectedWebPart;
}

But, be warned. 但是,请注意。 Almost any time that you are basing your logic on the type is a bad design smell! 几乎在任何时候都将逻辑基于类型是不对的!

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

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