PDA

View Full Version : تشخیص string بودن



meitti
یک شنبه 13 بهمن 1387, 13:54 عصر
سلام
ایا تابعی هست که اگر بهش یه اطلاعاتی دادیم نشون بده که این اطلاعات string هست یا نه

Mehdi Asgari
یک شنبه 13 بهمن 1387, 16:10 عصر
باید از as یا is استفاده کنی و مسلما باید اون چیزی که میخوای تستش کنی Reference Type باشه
مثال:


int x = 10;
string s = "Hello";
Action a = delegate { Console.WriteLine("Wow"); };
object o1 = x;
object o2 = s;
object o3 = a;

Console.WriteLine(o1 is string); //False
Console.WriteLine(o2 is string); //True
Console.WriteLine(o3 is string); //False

// Or:
string str = o1 as String;
if (String.IsNullOrEmpty(str))
Console.WriteLine("o1 is not a string");
else
Console.WriteLine(str);
// ditto for others