2014-07-09 44 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

相關問題