通用方法根据输入参数返回值
我是使用泛型类的新手。这是我的问题:
我有几个枚举,例如: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;
}
}
}
是否可以开发这样的方法?
预先感谢,
I'm new to using generic classes. Here is my question:
I have several enumerations like: x.PlatformType, y.PlatformType, z.PlatformType etc...
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;
}
}
}
Is it possible to develop a method like this?
Thank in advance,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
既然您知道它是一个枚举,最简单的事情就是使用
Enum.TryParse
:注意,我删除了
Type
参数,因为我假设它是由T 给出的
。也许让该方法通用而不是整个类对您来说会更好(取决于使用场景) - 像这样:Since you know it's an Enum, the simplest thing would be to use
Enum.TryParse
:Note, I removed the
Type
parameter because I assumed it was given byT
. Perhaps it would be better for you (depends on usage scenario) to make the method generic, and not the whole class - like this: