2012-01-23 100 views
1

我是使用泛型類的新手。這裏是我的問題:通用方法根據輸入參數返回值

我有幾個枚舉,如:x.PlatformType,y.PlatformType,z.PlatformType等等

public class Helper<T> 
{ 
    public T GetPlatformType(Type type) 
    { 
     switch (System.Configuration.ConfigurationManager.AppSettings["Platform"]) 
     { 
      case "DVL": 
       return // if type is x.PlatformType I want to return x.PlatformType.DVL 
         // if type is y.PlatformType I want to return y.PlatformType.DVL 
         // etc 
      default: 
       return null; 
     } 
    } 
} 

是否可以開發這樣的方法?

預先感謝,

+0

爲什麼你有幾個類似的枚舉?配置中的字符串是否總是像您的示例中那樣完全是枚舉值的名稱? –

+0

其實他們不是我的。這些類型來自幾個Web服務引用。 – anilca

回答

4

既然你知道它是一個枚舉,最簡單的做法是使用Enum.TryParse

public class Helper<T> where T : struct 
{ 
    public T GetPlatformType() 
    { 
     string platform = System.Configuration.ConfigurationManager.AppSettings["Platform"]; 
     T value; 
     if (Enum.TryParse(platform, out value)) 
      return value; 
     else 
      return default(T); // or throw, or something else reasonable 
    } 
} 

注意,我刪除了Type參數,因爲我認爲它是由T給。也許這將是更好地爲您(取決於使用情況),以使該方法通用的,而不是整個類 - 這樣的:

public class Helper 
{ 
    public T GetPlatformType<T>() where T : struct 
    { ... } 
} 
+0

謝謝!我接受了你的建議! – anilca