通用方法根据输入参数返回值

发布于 2024-12-28 15:31:32 字数 622 浏览 1 评论 0原文

我是使用泛型类的新手。这是我的问题:

我有几个枚举,例如: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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

独自唱情﹋歌 2025-01-04 15:31:32

既然您知道它是一个枚举,最简单的事情就是使用 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
    { ... }
}

Since you know it's an Enum, the simplest thing would be to use 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
    }
}

Note, I removed the Type parameter because I assumed it was given by T. Perhaps it would be better for you (depends on usage scenario) to make the method generic, and not the whole class - like this:

public class Helper 
{
    public T GetPlatformType<T>() where T : struct
    { ... }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文