【问题标题】:C# Including large readonly arrays in Windows FormsC# 在 Windows 窗体中包含大型只读数组
【发布时间】:2016-11-30 22:43:28
【问题描述】:

首先,我是 C# 和 Windows 窗体编程的新手。我一直是 C 嵌入式系统程序员。

我正在编写一个 Winform 程序,我需要包含一个大型 (48Kb) 只读数据数组以进行模拟。我在我的 Form1 类声明的顶部有它,问题是它在我得到我的公共 Form1() 代码之前持续了 1500 行:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ScrollWave
{
    public partial class Form1 : Form
    {
        readonly byte[] wvSamps = 
        {
            0x94, 0xa5, 0xca, 0x62, 0x41, 0x28, 0x4c, 0x93, 0x09, 0x42, 0x00, 0x25, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x04, 0x01, 0x40, 0x10, 0x00, 0x00, 0x70, 0x0d, 0x58, 0x3e, 0xc6, 0xd1, 0x07, 0x9c, 
            0x94, 0xa3, 0x8a, 0x62, 0x41, 0x29, 0x4c, 0x94, 0xc9, 0x32, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x04, 0x01, 0x40, 0x10, 0x00, 0x00, 0x70, 0x0d, 0x58, 0x3e, 0xc6, 0xd2, 0x08, 0x0c, 

在“C”中,我可以将它作为#include 文件包含在内,这样我就不必向下滚动 1500 行来获取我正在处理的代码。如何包含大量只读数据而不必将其放在我的 Form1 类声明的顶部,这样我就可以避免向下滚动 1500 行来获取我正在处理的代码?谢谢!

【问题讨论】:

  • 您可以在public static class 中硬编码您的数组,但我建议您使用 json 对其进行序列化并从 json 文件中读取它。
  • 为什么不为您尝试使用的 byte[] 创建一个单独的静态类......并创建该类以便它共享相同的命名空间ScrollWave
  • 考虑将您的数据放入二进制文件中并将其添加为资源。这将为您提供一个名为Resources.wvSampsbyte[] 属性,您可以访问该属性。见How to: Add or Remove Resources

标签: c# winforms visual-studio-2010


【解决方案1】:

例如,只需创建一个名为 ArrayData.cs 的新类文件,并将该类中的数据声明为静态字段:

public static class ArrayData
{
    public static byte[] WvSamps = {0x94, 0xa5, 0xca, 0x62, 0x41, 0x28, 0x4c, 0x93, 0x09, 0x42};
}

然后你可以在你的表单中使用它:

public partial class Form1 : Form
{
    public void DoSomethingWithData()
    {
        for(var i = 0; i < ArrayData.WvSamps.Length; i++)
        {
            //process your data here...
        }
    }
}

希望这会有所帮助!

【讨论】:

  • 好的,抱歉,我是 Visual Studio 的真正菜鸟,我假设我会在另一个 .cs 文件中创建这个类并将其添加到我的项目中。我正在使用 VS 2010 Express,但我很累,不知道如何将文件添加到我的项目中。我的学习是通过阅读 Stephens C# Programming with Visual Studio 2010。感谢您的帮助,如果我能完成一些简单的事情,我应该正在路上。
  • @DaleH。只需右键单击您的项目并选择添加 -> 新项目。然后搜索类,设置名称并单击添加按钮。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
相关资源
最近更新 更多