使用 C# 4.0。我想将 的实例转换MyBuffer<int>
为 的实例MyBuffer<float>
。转换器必须足够通用以处理其他基本类型。
我希望这个(或等效的解决方案)能够工作。如何?
var b1 = MyBuffer.Create(new int[100]);
var b2 = Convert.ChangeType(b1, typeof(MyBuffer<float>));
var b3 = Convert.ChangeType(b2, typeof(MyBuffer<byte>));
考虑MyBuffer
类:
public class MyBuffer
{
public static MyBuffer<T> Create<T>(T[] buffer)
where T : struct, IComparable, IConvertible
{
return new MyBuffer<T>(buffer);
}
}
public class MyBuffer<T> : IConvertible
where T : struct, IComparable, IConvertible
{
public T[] Buffer
{
get;
set;
}
public MyBuffer()
{
}
public MyBuffer(T[] buffer)
{
Buffer = buffer;
}
public object ToType(Type conversionType, IFormatProvider provider)
{
if (conversionType == GetType())
return this;
// First problem: Determine if the type is MyBuffer<>.
// if (conversionType == typeof(MyBuffer<>))
{
if (conversionType.IsGenericType && conversionType.GetGenericArguments().Length > 0)
{
var bufferType = conversionType.GetGenericArguments()[0];
dynamic newBuffer = Buffer.
Select(s => Convert.ChangeType(s, bufferType))
.ToArray();
// Second problem: Our dynamic variable will produce an exception here.
return MyBuffer.Create(newBuffer);
}
}
throw new InvalidCastException();
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//
// For completeness...
//
public TypeCode GetTypeCode()
{
throw new NotImplementedException();
}
public bool ToBoolean(IFormatProvider provider)
{
throw new NotImplementedException();
}
public byte ToByte(IFormatProvider provider)
{
throw new NotImplementedException();
}
public char ToChar(IFormatProvider provider)
{
throw new NotImplementedException();
}
public DateTime ToDateTime(IFormatProvider provider)
{
throw new NotImplementedException();
}
public decimal ToDecimal(IFormatProvider provider)
{
throw new NotImplementedException();
}
public double ToDouble(IFormatProvider provider)
{
throw new NotImplementedException();
}
public short ToInt16(IFormatProvider provider)
{
throw new NotImplementedException();
}
public int ToInt32(IFormatProvider provider)
{
throw new NotImplementedException();
}
public long ToInt64(IFormatProvider provider)
{
throw new NotImplementedException();
}
public sbyte ToSByte(IFormatProvider provider)
{
throw new NotImplementedException();
}
public float ToSingle(IFormatProvider provider)
{
throw new NotImplementedException();
}
public string ToString(IFormatProvider provider)
{
throw new NotImplementedException();
}
public ushort ToUInt16(IFormatProvider provider)
{
throw new NotImplementedException();
}
public uint ToUInt32(IFormatProvider provider)
{
throw new NotImplementedException();
}
public ulong ToUInt64(IFormatProvider provider)
{
throw new NotImplementedException();
}
}
在我上面的代码中,有两个主要问题需要解决:
- 你如何确定一个
Type
变量是否等于SomeType<T>
任意值T
? - 是否可以调用
T
设置为某个Type
变量的模板化函数?