Re: Getting a byte array from a generic class
Peter Ritchie <[email protected]> Tue, 18 May 2010 12:55:13 -0400
| Newsgroups | gmane.comp.windows.devel.dotnet.advanced |
|---|---|
| Message-ID | <8747028595473161.WA.advanced.dotnet.discuss.develop.comPETERRITCHIE.COM@peach.ease.lsoft.com> |
Rather than the bad smell of a type comparison, I prefer to use a more ob=
ject-oriented approach with polymorphism (overloading in this example). =
But, since we're dealing with a generic class that's trying to use a non-=
generic method; this get's a little tricky.=20=20
If you're using .NET 4.0, you can create a dynamic variable of the value =
and let the runtime deal with finding the overload. For example:
=09public abstract class NumericNtcipObject<T> where T : struct
=09{
=09=09private readonly T value;
=09=09protected NumericNtcipObject(T value)
=09=09{
=09=09=09this.value =3D value;
=09=09}
=09=09private static byte[] ToArray(int v)
=09=09{
=09=09=09return BitConverter.GetBytes(v);
=09=09}
=09=09private static byte[] ToArray(uint v)
=09=09{
=09=09=09return BitConverter.GetBytes(v);
=09=09}
=09=09//...
=09=09public byte[] ValueAsByteStream()
=09=09{
=09=09=09dynamic temp =3D value;
=09=09=09try
=09=09=09{
=09=09=09=09return ToArray(temp);
=09=09=09}
=09=09=09catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
=09=09=09{
=09=09=09=09return null;=09
=09=09=09}
=09=09}
=09}
If you're not using .NET 4.0 (and using .NET 3.x) then you can use reflec=
tion to do the same thing that the dynamic runtime would do (which is the=
visitor pattern or double-dispatch):
=09public abstract class NumericNtcipObject<T> where T : struct
=09{
=09=09private readonly T value;
=09=09protected NumericNtcipObject(T value)
=09=09{
=09=09=09this.value =3D value;
=09=09}
=09=09protected static byte[] ToArray(int v)
=09=09{
=09=09=09return BitConverter.GetBytes(v);
=09=09}
=09=09protected static byte[] ToArray(uint v)
=09=09{
=09=09=09return BitConverter.GetBytes(v);
=09=09}
=09=09//...
=09=09public byte[] ValueAsByteStream()
=09=09{
=09=09=09var method =3D from m in GetType().GetMethods(BindingFlags.NonPu=
blic | BindingFlags.Static | BindingFlags.FlattenHierarchy)
=09=09=09=09=09=09 where m.Name =3D=3D "ToArray"
=09=09=09=09=09=09=09 && m.GetParameters().Length =3D=3D 1
=09=09=09=09=09=09=09 && value.GetType().IsAssignableFrom
=09=09=09=09=09=09=09=09=09(m.GetParameters()[0].ParameterType)
=09=09=09=09=09=09=09 && m.ReturnType =3D=3D typeof(byte[])
=09=09=09=09=09=09 select m;
=09=09=09return (byte[])method.Single().Invoke(this, new object[] { value=
});
=09=09}
=09}
If you're prior to .NET 3.0, convert the LINQ statement to something that=
will work in .NET 2.0.
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
View archives and manage your subscription(s) at http://peach.ease.lsoft.com/archives