简体   繁体   中英

How to write the constraints for a generic class

There is a generic class XXValue like this, where the Type T can be value type or reference type, eg int, string, struct object

public class XXValue<T>
{
   public T DefaultValue;
}

And there is another generic class XXAttribute

public class XXAttribute<T>
{
   public T Value;
}

But the type T for XXAttribute should be the class or sub-class of type XXValue , so how to write the where statement for XXAttribute ? Which one is correct?

public class XXAttribute<T> where T : XXValue<T>

public class XXAttribute<VT, AT> where AT : XXValue<VT>

But the type T for XXAttribute should be the class or sub-class of type XXValue

Given this statement, it should be the second one.

public class XXAttribute<TBase, T> where T : XXValue<TBase>
{
    public T Value;
}

This specifies that the type parameter for XXAttribute should inherit from XXValue . But since XXValue is also a generic type, you need to specify its type parameter in XXAtribute also, as TBase , and pass it along.


Alternatively (it's hard to tell given the scope of the question, but you could possibly) change how Value is defined:

public class XXAttribute<TBase>
{
    public XXValue<TBase> Value;
}

Second would be correct as otherwise it is confusing for the compiler to know the value of T, where on one hand T is XXValue<T> and on the other hand T is int .

public class XXAttribute<V, T> where T : XXValue<V>
{
    public T Value;
}

Usage:

XXAttribute<int, XXValue<int>> attr = new XXAttribute<int, XXValue<int>>();

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