11 HAZİRAN 2009, PERŞEMBE
Kontrol türü: tür, GetType ya?
Birçok kişi şu kodu kullanın gördüm:
Type t = typeof(obj1);
if (t == typeof(int))
// Some code here
Ama şunu da yapabilirsin biliyorum:
if (obj1.GetType() == typeof(int))
// Some code here
Ya da bu:
if (obj1 is int)
// Some code here
Şahsen, son bir temiz olan ama kaçırdığım bir şey mi hissediyorum? Hangisini kullanmak en iyisidir, yoksa kişisel tercih mi?
CEVAP
11 HAZİRAN 2009, PERŞEMBE
Tüm farklı.
typeof
Bir tür adı derleme zamanında belirtin) alır.GetType
örnek çalışma zamanı tür alır.is
eğer bir örnek kalıtım ağacı ise true değerini döndürür.
Örnek
class Animal { }
class Dog : Animal { }
void PrintTypes(Animal a) {
print(a.GetType() == typeof(Animal)) // false
print(a is Animal) // true
print(a.GetType() == typeof(Dog)) // true
}
Dog spot = new Dog();
PrintTypes(spot);
Ne
typeof(T)
hakkında? Ayrıca derleme zamanında çözümlenir?
Evet. T ifade türü nedir her zaman. Unutmayın, genel bir yöntem temelde uygun tip yöntemler bir sürü. Örnek:
string Foo<T>(T object) { return typeof(T).Name; }
Animal probably_a_dog = new Dog();
Dog definitely_a_dog = new Dog();
Foo(probably_a_dog); // this calls Foo<Animal> and returns "Animal"
Foo<Animal>(probably_a_dog); // this is exactly the same as above
Foo<Dog>(probably_a_dog); // !!! This will not compile. The parameter expects a Dog, you cannot pass in an Animal.
Foo(definitely_a_dog); // this calls Foo<Dog> and returns "Dog"
Foo<Dog>(definitely_a_dog); // this is exactly the same as above.
Foo<Animal>(definitely_a_dog); // this calls Foo<Animal> and returns "Animal".
Foo((Animal)definitely_a_dog); // this does the same as above, returns "Animal"
Bunu Paylaş:
Nasıl javascript bir değişkeni fonksiy...
Nasıl bir değişken türü olmadığını kon...
C#, nasıl bir tip, bir alt VEYA bir ne...
Nasıl kullanıcı-tanımlamak SQL Server ...
Eğer Türü örnek C null bir numaralama ...