简体   繁体   中英

Why sealed classes are not allowed to be generic type constraints?

I just wanted to know why sealed classes are not allowed to be generic type constraints?

Let's suppose i have a simple code snippet in c# as bellow

 public sealed class Base
{
    public Base() { }
}

public class Derived<T>
        where T : Base
{
    public Derived() { }
}

When i am instantiating the Derivedclass i am getting 'Base' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.

Because then there's no point in it being generic. T could only be Base , so you might as well make it a non-generic type to start with.

Why would you want Derived to be generic here? Why would you want a type called Base (implying that it should be a base type) to be sealed?

Because T will never have child classes! There's no point to have such kind of generic.

The compiler doesn't want to go through the trouble of making something generic if there's only one class it can ever be. Note that one can use a sealed class as a generic constraint if the sealed class is passed as a type parameter. For example, if one has a class

Class Foo(Of T, U As T)

one may create an instance of that class where both generic type parameters are the same sealed type, since one could also create instances where the type parameters refer to different types.

T cant be anything else but Base . So, whats the point making it Generic ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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