تبليغاتX
جادوي سي شارپ
فرض کنید که تو برنامتون یه enum دارید که شامل برندهای موبایله و کابر باید نام برند مورد نظرشو وارد کنه و شما بر اساس اون واکنش نشون بدید.

enum MobileBrands : short
{
Nokia,
SonyEricson,
HTC
};


در این صورت برای تبدیل رشته ورودی به enum از چه روشی استفاده می کنید؟ اگه رشته ورودی را مستقیما بخواهید توی متغیری از جنس enum بریزید (مثل کد زیر)

static void Main(string[] args)
{
MobileBrands brands;
string brandName = Console.ReadLine();
brands=brandName;
}


خطای زیر اتفاق میفته:

Cannot implicitly convert type 'string' to 'EnumConvert.MobileBrands'

راه دوم اینه که با استفاده از switch متغیر مورد نظر را مقداردهی کنیم:

static void Main(string[] args)
{
MobileBrands brands;
string brandName = Console.ReadLine();
switch(brandName)
{
case "HTC":
brands=MobileBrands.HTC;
break;
case "Nokia":
brands=MobileBrands.Nokia;
break;
case "SonyErricson":
brands=MobileBrands.SonyErricson;
break;
}
}


اما راه سوم و ساده ترین راه استفاده از متد Enum.Parse است. به مثال زیر توجه کنید:

static void Main(string[] args)
{
MobileBrands brands;
string brandName = Console.ReadLine();
brands = (MobileBrands)Enum.Parse(typeof(MobileBrands), brandName);
}


اگه روش سوم را با Generic ادغام کنیم می تونیم متدی بنویسیم که هر رشته ای را به enum مورد نظر تبدیل کنه:

public static T StringToEnum(string paranName)
{
return (T)Enum.Parse(typeof(T), paranName);
}


به نحوه استفاده از این متد توجه کنید:

static void Main(string[] args)
{
MobileBrands brands;
string brandName = Console.ReadLine();
brands=StringToEnum(brandName);
}


+ نوشته شده در  شنبه نهم شهریور 1387ساعت 0:15  توسط ققنوس  |