When writing generic methods and functions, I have seen the Where type constraint written as
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?
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.
Consider this from 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
.
For instance this is the declaration of Int32 structure:
[SerializableAttribute]
[ComVisibleAttribute(true)]
public struct Int32 : IComparable, IFormattable,
IConvertible, IComparable<int>, IEquatable<int>
as you can see here .
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.