2014-07-09 70 views
1

当编写通用的方法和功能,我看到写为什么类的类型约束实现,如果一个泛型类型约束也必须实现在C#中的接口

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

何处类型约束
public static void MyMethod<T>(params T[] newVals) where T : class, IMyInterface 

'类'类型约束添加任何东西 - 我不认为一个结构可以实现一个接口,但我可能是错的?

谢谢

+1

是结构'can'实现接口。 –

+0

是的,结构可以实现接口。请参阅:[Int32结构](http://msdn.microsoft.com/en-us/library/system.int32(v = vs.110).aspx) –

+1

'Enumerator'是一个结构的示例,它实现了一个接口。 http://stackoverflow.com/questions/521298/when-to-use-struct-in-c –

回答

2

A struct可以实现一个接口,因此具有双重约束是非常合理的,要求泛型类型T既是class也是实现指定的接口。

考虑这个从Dictionary

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

结构可以实现接口。因此,这

where T : class, IMyInterface 

要求两个类型Tclass并实现了一个名为IMyInterface的接口class

举例来说,这是的Int32结构的声明:

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

,你可以看到here

+0

谢谢 - 我会标记你作为答案(两个答案都清楚地说明了我的假设错误),但是Dommer在1分钟前得到 – Brent

+0

@Brent不是一个问题的家伙。 – Christos

相关问题