简体   繁体   English

如果泛型类型约束还必须在c#中实现接口,那么类类型约束会实现什么?

[英]What does the class type constraint achieve if a generic type constraint must also implement an interface in c#

When writing generic methods and functions, I have seen the Where type constraint written as 在编写泛型方法和函数时,我已经看到Where类型约束被写为

public static void MyMethod<T>(params T[] newVals) where T : IMyInterface

and also 并且

public static void MyMethod<T>(params T[] newVals) where T : class, IMyInterface

does the 'class' type constraint add anything - I don't imagine a struct could ever implement an interface, but i could be wrong? 'class'类型约束是否添加任何东西 - 我不认为结构可以实现接口,但我可能是错的?

Thank you 谢谢

A struct can implement an interface, so it's quite reasonable to have the double constraint of requiring the generic type T to be both a class and to implement the specified interface. struct可以实现一个接口,因此拥有双重约束是非常合理的,它要求泛型类型T既是一个class又是实现指定的接口。

Consider this from Dictionary : Dictionary考虑这个:

[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Enumerator : 
    IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable, 
    IDictionaryEnumerator, IEnumerator
{
    //  use Reflector to see the code
}

Structs can implement interfaces. 结构可以实现接口。 So this 所以这

where T : class, IMyInterface

demands both the type T be a class and a class which implements the interface called IMyInterface . 要求类型T是一个class ,一个class实现名为IMyInterface

For instance this is the declaration of Int32 structure: 例如,这是Int32结构的声明:

[SerializableAttribute]
[ComVisibleAttribute(true)]
public struct Int32 : IComparable, IFormattable, 
                      IConvertible, IComparable<int>, IEquatable<int>

as you can see here . 你可以在这里看到。

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

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