質問
これはばかげた質問ですが、このコードを使用して、特定のタイプかどうかを確認できます...
if (child is IContainer) { //....
<!> quot; NOT <!> quot;をチェックするよりエレガントな方法はありますか?インスタンス?
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...
他のヒント
次の方法で実行できます。
object a = new StreamWriter("c:\\temp\\test.txt");
if (a is TextReader == false)
{
Console.WriteLine("failed");
}
elseだけを使用するのではない理由
if (child is IContainer)
{
//
}
else
{
// Do what you want here
}
見慣れたシンプルなものですか?
方法は問題ありませんが、拡張メソッドのセットを作成して<!> quot;「NOT」インスタンスをチェックするよりエレガントな方法をできます。<!> quot ;
public static bool Is<T>(this object myObject)
{
return (myObject is T);
}
public static bool IsNot<T>(this object myObject)
{
return !(myObject is T);
}
次のように書くことができます:
if (child.IsNot<IContainer>())
{
// child is not an IContainer
}
Uい?同意しません。他の唯一の方法(個人的には<!> quot; uglier <!> quot;だと思います):
var obj = child as IContainer;
if(obj == null)
{
//child "aint" IContainer
}
is
演算子はブール結果に評価されるため、boolでできることなら何でもできます。無効にするには、!
演算子を使用します。なぜこれだけに別の演算子を使いたいのですか?
拡張メソッドIsNot<T>
は、構文を拡張する良い方法です。覚えておいてください
var container = child as IContainer;
if(container != null)
{
// do something w/ contianer
}
次のようなことを行うよりもパフォーマンスが優れています
if(child is IContainer)
{
var container = child as IContainer;
// do something w/ container
}
あなたの場合、メソッドから戻ってくるので問題ではありません。つまり、型のチェックとその直後の型変換の両方を行わないように注意してください。
通常はIS演算子が最善の方法ですが、状況によっては使用できる代替手段があります。 as演算子を使用して、nullをテストできます。
MyClass mc = foo as MyClass;
if ( mc == null ) { }
else {}
これは括弧の問題を回避しませんが、Googleを介してここにアクセスする人々のために、コードの残りの部分を少しきれいにするための新しい構文(C#7以降)が存在することに注意してください:
if (!(DocumentPart is IContainer container)) { return; }
foreach(DocumentPart child in container.Children) {
...
これにより、ダブルキャスト、nullチェック、およびnullになる可能性のあるスコープで変数を使用できるようにします。
これはまだ言及されていません。それは機能し、!(child is IContainer)
if (part is IContainer is false)
{
return;
}
if (child is IContainer ? false : true)