繁体   English   中英

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

[英]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.

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