C#Struct无参数构造函数?看看我需要做什么 [英] C# Struct No Parameterless Constructor? See what I need to accomplish

查看:368
本文介绍了C#Struct无参数构造函数?看看我需要做什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  [StructLayout(LayoutKind.Sequential)] 
public struct valTable
{
public byte type;
公共字节映射;
public byte spare1;
public byte spare2;
public int par;
public int min;
public byte [] name;
public valTable()
{
name = new byte [24];
}
}

上面的代码不会编译,因为VS 2005会抱怨Structs不能包含显式的无参数构造函数。为了将这个结构传递给我的DLL,我必须传递一个结构体的数组,像这样 valTable [] val = new valTable [281];



我想做的是当我说 new 时,构造函数被调用,它创建一个字节数组,就像我正在尝试证明是因为DLL正在每个维度中寻找大小为24的字节数组。



如何实现?

解决方案

您可以使用固定大小缓冲区 - 我怀疑你真的想要的,以便在struct中获取数据inline(而不是其他地方对数组的引用)。

  public fixed byte name [24]; 

您将需要将结构声明为不安全。



请注意,任何需要调用静态方法或提供任何类型的自定义构造函数的解决方案都将失败,您的明确目标是能够创建一个这些结构体的数组。


I am using a struct to pass to an unmanaged DLL as so -

[StructLayout(LayoutKind.Sequential)]
        public struct valTable
        {
            public byte type;
            public byte map;
            public byte spare1;
            public byte spare2;
            public int par;
            public int min;
            public byte[] name;
            public valTable()
            {
                name = new byte[24];
            }
        }

The code above will not compile because VS 2005 will complain that "Structs cannot contain explicit parameterless constructors". In order to pass this struct to my DLL, I have to pass an array of struct's like so valTable[] val = new valTable[281];

What I would like to do is when I say new, the constructor is called and it creates an array of bytes like I am trying to demonstrate because the DLL is looking for that byte array of size 24 in each dimension.

How can I accomplish this?

解决方案

You can use a fixed size buffer - which I suspect you really want anyway, so as to get the data "inline" in the struct (rather than a reference to an array elsewhere).

public fixed byte name[24];

You'll need to declare the struct as unsafe as well though.

Note that any "solution" which requires calling a static method or providing any kind of custom constructor will fail with your explicit goal of being able to create an array of these structs.

这篇关于C#Struct无参数构造函数?看看我需要做什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆