简体   繁体   English

C#:如何从对象变量中的值获取类型变量并在类型变量中输入类型?

[英]C#: How to get typed variable from value in Object variable and type in Type variable?

  1. I have a value in a variable of type Object . 我在Object类型的变量中有一个值。
  2. I have its type in a variable of type Type . 我在Type的变量中有它的Type
  3. Type can be only among standard system types (Int32, Int64, etc..) 类型只能在标准系统类型(Int32,Int64等)中。

Q. I want to get bytes array representing this value. 问:我想获取代表此值的字节数组。 I'm trying to use BitConverter.GetBytes for that, but it requires a typed variable. 我正在尝试使用BitConverter.GetBytes ,但是它需要一个类型化的变量。 Is there a way to get typed variable dynamically having a value and type in separate variables? 有没有一种方法可以动态地获取具有值和类型的单独变量的类型变量?

Thank you. 谢谢。

If you don't want to switch on each type and call the appropriate method, which is the fastest way, you could use reflection, albeit a bit slower: 如果您不想switch每种类型并调用适当的方法(这是最快的方法),则可以使用反射,尽管会慢一些:

byte[] GetBytes(object obj)
{
    var type = obj.GetType();
    return (byte[])typeof(BitConverter)
        .GetMethods(BindingFlags.Public | BindingFlags.Static)
        .Single(m => m.Name == "GetBytes" && m.GetParameters().Single().ParameterType == type)
        .Invoke(null, new object[] { obj });
}

Calling GetBytes((short)12345) produces new byte[] { 0x39 ,0x30 } . 调用GetBytes((short)12345)产生new byte[] { 0x39 ,0x30 }

public byte[] GetAnyBytes(dynamic myVariable) {
     return BitConverter.GetBytes(myVariable)
}

dynamic is essentially "I don't know what type this could be, check it at run time". dynamic本质上是“我不知道它可能是什么类型,请在运行时检查它”。 Obviously, this is slower than using real types, but it is more flexible. 显然,这比使用实类型慢,但更灵活。 Also, requires C# 4.0. 另外,还需要C#4.0。

You could try something like this to get a byte array. 您可以尝试类似这样的操作来获取字节数组。

public static byte[] Object2ByteArray(object o)
{
    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
    {
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = 
            new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        bf.Serialize(ms, o);
        return ms.ToArray();
    }
}

Although based on your description you may have made some poor implementation choices elsewhere. 尽管根据您的描述,您可能在其他地方做出了一些糟糕的实现选择。

found here . 这里找到。

I'm concerned that you're trying to interact with another device using a binary format. 我担心您正在尝试使用二进制格式与另一台设备进行交互。 Assuming the receiver of your data is not .NET, binary representations of data types varies from one device to another. 假设数据的接收者不是.NET,则数据类型的二进制表示形式在一个设备之间会有所不同。 I think you're better off representing this information in text, and using a parser to interpret the text. 我认为最好以文本形式表示此信息,并使用解析器来解释文本。

You can use MemoryMappedFile 您可以使用MemoryMappedFile

private byte[] GetBytes<T>(T obj) where T : struct
{
    int size = Marshal.SizeOf(typeof(T));
    using(var mmf = MemoryMappedFile.CreateNew("test", size))
    using(var acc = mmf.CreateViewAccessor())
    {
        acc.Write(0, ref obj);
        var arr = new byte[size];
        for (int i = 0; i < size; i++)
            arr[i] = acc.ReadByte(i);
        return arr;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM