This is a silly question, but you can use this code to check if something is a particular type...
if (child is IContainer) { //....
Is there a more elegant way to check for the "NOT" instance?
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) {
Yes, yes... silly question....
Because there is some question on what the code looks like, it's just a simple return at the start of a method.
public void Update(DocumentPart part) { part.Update(); if (!(DocumentPart is IContainer)) { return; } foreach(DocumentPart child in ((IContainer)part).Children) { //...etc...
Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.
C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).
if(!(child is IContainer))
is the only operator to go (there's no IsNot
operator).
You can build an extension method that does it:
public static bool IsA<T>(this object obj) { return obj is T; }
and then use it to:
if (!child.IsA<IContainer>())
And you could follow on your theme:
public static bool IsNotAFreaking<T>(this object obj) { return !(obj is T); } if (child.IsNotAFreaking<IContainer>()) { // ...
Since you're actually casting the value afterward, you could just use as
instead:
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...
You can do it this way:
object a = new StreamWriter("c:\\temp\\test.txt"); if (a is TextReader == false) { Console.WriteLine("failed"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With