我在寫一種特殊的System.IO.BinaryWriter
。這位作家應該能夠處理整數類型,包括Enum
和也是這些類型的集合。實現泛型方法來處理不同整型的集合的正確方法是什麼?
abstract class MyBinaryWriter
{
// ...
#region Methods: Basic Types: Writing
public abstract void Write(byte value);
public abstract void Write(ushort value);
public abstract void Write(uint value);
public abstract void Write(ulong value);
public abstract void Write(string value);
#endregion
#region Methods: Complex Types: Writing
public virtual void Write<T>(ICollection<T> collection)
{
// first write the 32-bit-unsigned-length prefix
if (collection == null || collection.Count == 0)
{
Write((uint)0);
}
else
{
Write((uint)collection.Count);
// then write the elements, if any
foreach (var item in collection)
; // What here? Obviously Write(item) doesn't work...
}
}
// ...
}
解決此問題的最佳方法是什麼?使用泛型的解決方案比爲每個整型和每個枚舉類型編寫一個重載要好得多。可能的解決方案如下,但我不喜歡這麼多,並有潛在的性能問題。要做到這一點
#region Methods: Complex Types: Writing
public virtual void Write<T>(ICollection<T> collection) where T : IConvertible
{
// first write the 32-bit-unsigned-length prefix
if (collection == null || collection.Count == 0)
{
Write((uint)0);
}
else
{
Write((uint)collection.Count);
// get the method for writing an element
Action<T> write = null;
var type = typeof(T);
if (type.IsEnum)
type = Enum.GetUnderlyingType(type);
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.SByte:
write = (x => Write((byte)(IConvertible)x.ToByte(null)));
break;
case TypeCode.Int16:
case TypeCode.UInt16:
write = (x => Write((ushort)(IConvertible)x.ToUInt16(null)));
break;
case TypeCode.Int32:
case TypeCode.UInt32:
write = (x => Write((uint)(IConvertible)x.ToUInt32(null)));
break;
case TypeCode.Int64:
case TypeCode.UInt64:
write = (x => Write((ulong)(IConvertible)x.ToUInt64(null)));
break;
default:
Debug.Fail("Only supported for integral types.");
break;
}
// then write the elements, if any
foreach (var item in collection)
write(item);
}
}
我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –