C# 将 T 限制为字符串和整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/455050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 04:01:30  来源:igfitidea点击:

Restricting T to string and int?

c#classgenericstypes

提问by Mats

I have built myself a generic collection class which is defined like this.

我已经为自己构建了一个通用集合类,其定义如下。

public class StatisticItemHits<T>{...}

This class can be used with intand stringvalues only. However this

此类只能与intstring值一起使用。然而这

public class StatisticItemHits<T> where T : string, int {...}

won't compile. What am I doing wrong?

不会编译。我究竟做错了什么?

采纳答案by driAn

The type restriction is meant to be used with Interfaces. Your sample suggests that you want to allow classes that inherit from int and string, which is kinda nonsense. I suggest you design an interface that contains the methods you'll be using in your generic class StatisticItemHits, and use that interface as restriction. However I don't really see your requirements here, maybe you could post some more details about your scenario?

类型限制旨在与接口一起使用。您的示例表明您希望允许从 int 和 string 继承的类,这有点无稽之谈。我建议您设计一个接口,其中包含您将在通用类 StatisticItemHits 中使用的方法,并将该接口用作限制。但是,我在这里并没有真正看到您的要求,也许您可​​以发布有关您的场景的更多详细信息?

回答by tuinstoel

Not possible to do this with 'where'. You can't do an 'or'.

不可能用'where'来做到这一点。你不能做“或”。

回答by chakrit

You cannot restrict it to string and int from the where clause. You can check it in the constructor, but that is probably not a good place to be checking. My approach would be to specialize the class and abstract the class creation into a (semi-)factory pattern:

您不能将它限制为来自 where 子句的 string 和 int。您可以在构造函数中检查它,但这可能不是检查的好地方。我的方法是专门化类并将类创建抽象为(半)工厂模式:

class MyRestrictedGeneric<T>
{
    protected MyRestrictedGeneric() { }


    // Create the right class depending on type T
    public static MyRestrictedGeneric<T> Create<T>()
    {
        if (typeof(T) == typeof(string))
            return new StringImpl() as MyRestrictedGeneric<T>;

        if (typeof(T) == typeof(int))
            return new IntImpl() as MyRestrictedGeneric<T>;

        throw new InvalidOperationException("Type not supported");
    }


    // The specialized implementation are protected away
    protected class StringImpl : MyRestrictedGeneric<string> { }
    protected class IntImpl : MyRestrictedGeneric<int> { }
}

This way you can limit the class's usage to just string and int internallyinside your class.

通过这种方式,您可以将类的使用限制为仅在类内部使用 string 和 int 。

回答by Ruben

You could make StatisticItemHits<T>an abstract class and create two subclasses:

您可以创建StatisticItemHits<T>一个抽象类并创建两个子类:

StatisticItemHitsInt : StatisticItemHits<int>{}

StatisticItemHitsInt : StatisticItemHits<int>{}

StatisticItemHitsString : StatisticItemHits<string>{}

StatisticItemHitsString : StatisticItemHits<string>{}

That way there can only be an int and string-representation of StatisticItemHits

这样就只能有 StatisticItemHits 的 int 和 string 表示

回答by Sean Kearon

As others have said, you cannot use type restrictions in this way. What you can do is to specialise from your base type as follows:

正如其他人所说,您不能以这种方式使用类型限制。您可以做的是从您的基本类型中进行专门化,如下所示:

public class StatisticItemHits <T> { }

public class StringStatisticItemHits : StatisticItemHits<string> { }

public class IntegerStatisticItemHits : StatisticItemHits<int> { }

Also, as your base class is generic, you won't be able to use this to polymorphically. If you need to do this make StatisticItemHits implement an interface and use this to reference instances. Something like:

此外,由于您的基类是通用的,您将无法以多态方式使用它。如果你需要这样做,让 StatisticItemHits 实现一个接口并使用它来引用实例。就像是:

public class StatisticItemHits <T> : IStaticticItemHits { }

public interface IStatisticItemHits { }

回答by Keith

Given that you only have two types here I would go down an OO route here instead and just have two classes for the two types.

鉴于您在这里只有两种类型,我会在这里采用面向对象的路线,并且只有两种类型的两个类。

Generics are best used where the circumstances in which they can be applied are, you know, generic. They're a lot less use in circumstances like this.

泛型最适合在可以应用泛型的情况下使用,您知道,泛型。在这种情况下,它们的使用要少得多。

You can restrict to struct or class types only, and I do think that there need to be numeric or operator based restrictions (e.g. must support +=)

您只能限制为 struct 或 class 类型,我确实认为需要基于数字或运算符的限制(例如必须支持 +=)

Int and string are really quite different, certainly more different than int and double. It wouldn't make much sense for a generic class to support the immutable reference type of string and the value type of int without also supporting other types more similar to either of them.

int 和 string 真的很不一样,肯定比 int 和 double 更不同。如果泛型类支持字符串的不可变引用类型和 int 的值类型而不支持与它们更相似的其他类型,则没有多大意义。

回答by user3195206

Simply use:

只需使用:

where TSource : IEquatable<string>