开发者

Cannot convert type 'byte' to 'T'

开发者 https://www.devze.com 2023-03-12 21:39 出处:网络
am new with C# so i really dont know how to make it , but in C++ i was doing it like this template <typename T> writeInt(int location, T value){

am new with C# so i really dont know how to make it , but in C++ i was doing it like this

template <typename T> writeInt(int location, T value){
    *(T*)&buffer[location] = value;
}

in C# am trying to do the same

public void WriteInt<T>(int location,T value)
        {
            (T)buffer[location] = value;
        }

but am g开发者_C百科eting this error Cannot convert type 'byte' to 'T' so how can i do it, thanks


Firstly,

You should probably be using a MemoryStream and a BinaryWriter to write primitive types to a buffer. You can, as suggested, use the BitConverter class, but you'll end up with a lot of intermediate byte[] objects going that way.

byte[] buffer;

int value1 = 10;
double value2 = 20;
string value3 = "foo";

using(var ms = new System.IO.MemoryStream())
{
    using(var writer = new System.IO.BinaryWriter(ms))
    {
        writer.Write(value1);
        writer.Write(value2);
        writer.Write(value3);
    }
}

buffer = ms.ToArray();

(value1, value2, and value3 are just examples here to show you a couple of the various overloads available; you should look at the MSDN page on BinaryWriter for more information)

More importantly,

You're using pointer arithmetic in your C++ code; C# only provides true pointer functionality when running within an unsafe block, and you should avoid that if at all possible (which it is here). .NET works on references, not pointers, so you don't have as much control over the actual memory allocation.

To make a long story short, you can't do what you're trying to do in the way you're trying to do it.


To do what you want, I believe you'll need to do something like this:

byte[] buffer = new byte[8192] ;
void WriteInt<T>( int offset , T value)
{
  Type       tBitConvert = typeof(BitConverter) ;
  MethodInfo getBytes    = tBitConvert.GetMethod( "GetBytes" ,
                             BindingFlags.Static|BindingFlags.Public ,
                             Type.DefaultBinder , new Type[]{ typeof(T) } ,
                             null 
                             ) ;

  if ( getBytes == null ) throw new InvalidOperationException("invalid type") ;

  byte[] octets = (byte[]) getBytes.Invoke(null, new object[]{ value } ) ;

  Array.Copy( octets , 0 , buffer , offset , octets.Length ) ;
  return ;
}

But I think you you'd be better off — certainly more idiomatic — if you simply used System.IO.BinaryStream, subtyping it to provide the buffering you appear to want.


so i can say WriteInt or 32 etc , buffer = byte[]

What you have would not be allowed in either case.

If buffer is a byte array then you need to covert value to a byte array instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消