c# - 使用 Type 参数作为返回类型

标签 c# generics types

是否可以这样做:

public static T ToEnum<T>(this string s, Type T)
{
    return (T)Enum.Parse(typeof(T), s);
}

或者以其他方式,即使用参数 T 作为返回类型?

最佳答案

你可以这样做

public static class Extensions
{
    public static T ToEnum<T>(this string s) where T : struct
    {
        return (T)Enum.Parse(typeof(T), s);
    }
}

public enum TestEnum
{
    None,

    Special,
}

class Program
{
    static void Main(string[] args)
    {
        var x = TestEnum.Special.ToString();
        var y = x.ToEnum<TestEnum>(); // y will be TestEnum.Special
    }
}

关于c# - 使用 Type 参数作为返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8223959/

相关文章:

typescript - 如何从 typescript 中的类型中排除 getter only 属性

c# - 通过反射获取命名空间中的所有类型

c# - Polly 如何能够重新发送相同的 HTTP 请求?

c# - 从网站下载所有 PDF 文件

java - 在Java SpringBoot中,可以有一个通用的起始节点并稍后分配类型吗?

如果列中的预期字符数约为 150K,则为 Mysql 数据类型

Scala self 意识特征

c# - WebApi 返回 HTTP 响应后是否可以执行代码?

java.lang.Class 泛型和通配符

c# - 重载与泛型或多态性