简体   繁体   English

你能从c#中的泛型中获得特定类型的行为吗?

[英]Can you get type specific behavior from generics in c#?

I think it should be pretty clear what I want to do - get an explicit specialization for int and string , and in C++ this is trivial with explicit specialization - is it possible to get this same behavior in C#? 我认为应该很清楚我想要做什么 - 获得intstring的显式特化,而在C ++中,这是显而易见的专门化 - 是否有可能在C#中获得相同的行为? Assume I have a good reason for doing this and this is a trivial example of something broader in my program. 假设我有充分的理由这样做,这是我程序中更广泛的一个简单的例子。

static class ReturnConstant<T>
{
    public static T FiveOrHello()
    {
        if(typeof(T) == typeof(int))
        {
            return 5;
        }
        else if (typeof(T) == typeof(string))
        {
            return "Hello!";
        }
        else
        {
            throw new NotImplementedException("OH NO");
        }
    }
}

Edit: 编辑:

Here's the equivalent, perfectly legit c++ code: 这是完全合法的c ++代码:

template <typename T>
T giveConst();
template <>
int giveConst<int>() { return 5; }
template <>
std::string giveConst<std::string>() { return "Hello"; }

The only thing wrong with your implementation is that the C# compiler can't verify the type cast to T. 您的实现唯一的问题是C#编译器无法验证转换为T的类型。

But you can work around that like this: 但你可以解决这个问题:

static class ReturnConstant<T>
{
    public static T FiveOrHello()
    {
        if (typeof(T) == typeof(int))
        {
            return (T)(object)5;
        }
        else if (typeof(T) == typeof(string))
        {
            return (T)(object)"Hello!";
        }
        else
        {
            throw new NotImplementedException("OH NO");
        }
    }
}

No, it's impossible. 不,这是不可能的。 Generic T for class ReturnConstant<T> means, that ReturnConstant<int> and ReturnConstant<string> are different types. ReturnConstant<T>通用T表示ReturnConstant<int>ReturnConstant<string>是不同的类型。 And you can't return different types in common. 而且你不能回归不同的类型。

A concept you may be interested in is a discriminated union; 您可能感兴趣的概念是一个受歧视的联盟; it would allow you to return either an int or a string with a single type, but you'd have to check at runtime to work out which one actually got returned: 它将允许您返回一个int或一个单一类型的字符串,但您必须在运行时检查以确定实际返回的是哪一个:

sadly the concept doesn't currently exist in a way that can be efficiently implemented, requiring some language support, which is not yet added. 遗憾的是,这个概念目前还没有以可以有效实施的方式存在,需要一些尚未添加的语言支持。

https://github.com/dotnet/csharplang/issues/113 https://github.com/dotnet/csharplang/issues/113

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM