这是一个愚蠢的问题,但您可以使用此代码来检查某些东西是否是特定类型......
if (child is IContainer) { //....
有没有更优雅的方法来检查“NOT”实例?
if (!(child is IContainer)) { //A little ugly... silly, yes I know...
//these don't work :)
if (child !is IContainer) {
if (child isnt IContainer) {
if (child aint IContainer) {
if (child isnotafreaking IContainer) {
是啊是啊……愚蠢的问题……
因为有一些疑问从代码的外观来看,它只是方法开始处的简单返回。
public void Update(DocumentPart part) {
part.Update();
if (!(DocumentPart is IContainer)) { return; }
foreach(DocumentPart child in ((IContainer)part).Children) {
//...etc...
if(!(child is IContainer))
是唯一要走的操作员(没有IsNot
操作员)。
您可以构建一个扩展方法来执行此操作:
public static bool IsA<T>(this object obj) {
return obj is T;
}
然后用它来:
if (!child.IsA<IContainer>())
你可以遵循你的主题:
public static bool IsNotAFreaking<T>(this object obj) {
return !(obj is T);
}
if (child.IsNotAFreaking<IContainer>()) { // ...
更新(考虑OP的代码片段):
由于您实际上是在之后转换该值,因此您可以使用as
反而:
public void Update(DocumentPart part) {
part.Update();
IContainer containerPart = part as IContainer;
if(containerPart == null) return;
foreach(DocumentPart child in containerPart.Children) { // omit the cast.
//...etc...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)