[英]What does the class type constraint achieve if a generic type constraint must also implement an interface in c#
在编写泛型方法和函数时,我已经看到Where类型约束被写为
public static void MyMethod<T>(params T[] newVals) where T : IMyInterface
并且
public static void MyMethod<T>(params T[] newVals) where T : class, IMyInterface
'class'类型约束是否添加任何东西 - 我不认为结构可以实现接口,但我可能是错的?
谢谢
struct
可以实现一个接口,因此拥有双重约束是非常合理的,它要求泛型类型T
既是一个class
又是实现指定的接口。
从Dictionary
考虑这个:
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Enumerator :
IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable,
IDictionaryEnumerator, IEnumerator
{
// use Reflector to see the code
}
结构可以实现接口。 所以这
where T : class, IMyInterface
要求类型T
是一个class
,一个class
实现名为IMyInterface
。
例如,这是Int32结构的声明:
[SerializableAttribute]
[ComVisibleAttribute(true)]
public struct Int32 : IComparable, IFormattable,
IConvertible, IComparable<int>, IEquatable<int>
你可以在这里看到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.