小编Ofi*_*fir的帖子

如何在C#中编组具有未知长度字符串字段的结构

我得到一个字节数组,我需要将它解组为C#struct.我知道结构的类型,它有一些字符串字段.字节数组中的字符串如下所示:两个第一个字节是字符串的长度,然后是字符串本身.我不知道琴弦的长度.我知道它的Unicode!

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class User
{
  int Id;//should be 1
  String UserName;//should be OFIR
  String FullName;//should be OFIR
}
Run Code Online (Sandbox Code Playgroud)

字节数组如下所示:00,00,01,00,00,00,08,00,4F,00,46,00,49,00,52,00,00,00,08,00,4F,00 ,46,00,49,00,52,00,

我还发现这个链接有同样的问题未解决: 将二进制数据加载到结构中

谢谢大家,Ofir

c# struct marshalling unmarshalling

8
推荐指数
1
解决办法
1928
查看次数

如何在运行时发出事件

我希望生成(emit)类在运行时使用C#实现接口.

我已成功发出方法和属性,但我无法发出事件.

这是我想要发出的代码:

命名空间:TestInterfaces,Class:TestIImplementMe.

public event EventHandler SimpleEvent;
Run Code Online (Sandbox Code Playgroud)

这是生成的IL代码:

.event [mscorlib]System.EventHandler SimpleEvent
{
    .addon instance void TestInterfaces.TestIImplementMe::add_SimpleEvent(class [mscorlib]System.EventHandler)
    .removeon instance void TestInterfaces.TestIImplementMe::remove_SimpleEvent(class [mscorlib]System.EventHandler)
}

.method public final hidebysig specialname newslot virtual 
    instance void add_SimpleEvent (
        class [mscorlib]System.EventHandler 'value'
    ) cil managed 
{
    // Method begins at RVA 0x330c
    // Code size 48 (0x30)
    .maxstack 3
    .locals init (
        [0] class [mscorlib]System.EventHandler,
        [1] class [mscorlib]System.EventHandler,
        [2] class [mscorlib]System.EventHandler,
        [3] bool
    )

    IL_0000: ldarg.0
    IL_0001: ldfld class [mscorlib]System.EventHandler TestInterfaces.TestIImplementMe::SimpleEvent
    IL_0006: stloc.0
    // …
Run Code Online (Sandbox Code Playgroud)

c# events runtime reflection.emit

8
推荐指数
1
解决办法
1624
查看次数

Reflection Emit:如何将Attribute实例转换为CustomAttributeBuilder或CustomAttributeData

我创建了一个生成器类,它基于实现接口的接口构建代理类.

请参阅我在基于接口构建代理类的帖子而不实现它.

我很熟悉CustomAttributeData.GetCustomAttributes(MemberInfo target),当我读取Interface的成员并成功将它们导入代理时,我使用它.

我想在运行时向生成的类注入其他属性.我要求将属性实例注入代理中.

例如:

开发人员可以将其作为值传递:new ObsoleteAttribute("Demo", true),(它有一个空构造函数,但属性是只读的),我想将其转换为:

return new CustomAttributeBuilder(
               attribute.GetType().GetConstructor(Type[] {typeof (string), typeof (bool)}),
               new object[] {"Demo", true},
               new FieldInfo[0], 
               new object[0]);
Run Code Online (Sandbox Code Playgroud)

记住,我不知道给出了什么.

c# reflection reflection.emit

5
推荐指数
1
解决办法
3856
查看次数