2012-01-23 43 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