3

そのため、 C#を使用default(Foo)すると、クラスの認識された「まだ入力されていない」/空のインスタンスを取得できるようになりました。これがまったく同じかどうかはわかりnew Foo()ません。多くのライブラリクラスFoo.Emptyは、同様のインスタンスを返すプロパティも実装しています。そしてもちろん、どの参照型もを指すことができますnull。本当に、違いは何ですか?いつ正しいか間違っているか?より一貫性のある、またはより良いパフォーマンスは何ですか?オブジェクトが概念的に「プライムタイムの準備ができていない」かどうかを確認する場合、どのテストを使用する必要がありますか?誰もが持っているわけではありませんFoo.IsNullOrEmpty()

4

3 に答える 3

16

default(Foo) will return null when Foo is a class type, zero where Foo is a value type (such as int), and an instance of Foo with all fields initialized to their respective default() values where Foo is a struct. It was added to the language so that generics could support both value and reference types - more info at MSDN

Use default(Foo) when you're testing a T in the context of SomeClass<T> or MyMethod<T> and you don't know whether T will be value type, a class type or a struct.

Otherwise, null should mean "unknown", and empty should mean "I know this is empty". Use the Foo.Empty pattern if you genuinely need an empty - but non-null - instance of your class; e.g. String.Empty as an alternative to "" if you need to initialize some variable to the empty string.

Use null if you know you're working with reference types (classes), there's no generics involved, and you're explicitly testing for uninitialized references.

于 2008-10-09T19:54:38.803 に答える
2

default(Foo)値型と参照型の両方で機能します。 New Foo(), nullFoo.Empty()ません。これにより、たとえば、どちらを扱っているかわからない場合など、ジェネリック型で使用するのに適しています。しかし、ほとんどの参照型のケースでnullは、おそらく十分です。

于 2008-10-09T19:45:51.503 に答える
2

関連する実際の型がわかっている場合、または ": class" で制約された型パラメーターがある場合は、既知の値 (null、0 など) を使用するのが最も簡単です。

制約のない、または参照型以外の制約のある型パラメーターを取得したばかりの場合は、default(T) を使用する必要があります。

于 2008-10-09T20:11:10.050 に答える