我刚开始使用泛型类。这是我的问题:
我有几个枚举,例如: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;
}
}
}
是否可以开发出这样的方法?
提前致谢
请您参考如下方法:
既然你知道它是一个枚举,最简单的方法就是使用 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
{ ... }
}
