C#结构推荐

时间:2019-03-09 23:47:40

标签: c# visual-studio uwp

作为C#入门者,我正在编写UWP应用。该应用程序当前的运行情况完全符合预期,但是我想知道是否有更好的方法来声明我的图像数组 作为全球班级。我搜索了一个替代品几个小时,但没有找到符合我需要的示例。

下面是我的代码:

namespace myUWPapp
{
    public sealed partial class MainPage : Page
    {
        string[] imgImagesSourceFileName = { "images1.png", "image2.png", "image3.png", "image4.png", "image5.png" };
        string[] btnImagesSourceFileName = { "images6.png", "image7.png", "image8.png", "image9.png", "image10" };

        public MainPage()
        {
            this.InitializeComponent();
            ...
            ...
        }
        private string GetImageFileName(string[] array, int index)
        {
            string image = array[index];

            return image;
        }
        private void ReverseArray(string[] array)
        {
            Array.Reverse(array);
        }
        private void MethodeUsingGetImagesSourceFileName()
        {
            ...         
            string image = GetImageFileName(myArray, myIndex);
            ...         
        }
        private void MethodeUsingReverseArray()
        {
            ...
            ...
            ReversesArray(myImagesArray);
        }
    }
}   

期待其他选择,但不要忘记我在编码方面还是一个相对较新的人。

2 个答案:

答案 0 :(得分:1)

我检查了您的代码,我认为MethodeUsingGetImagesSourceFileNameMethodeUsingReverseArray不灵活。如果您只想处理字符串数组,则可以为图像数组创建ListExtensionList<string>

public static class ListExtension
{
    public static void InitializeImageArray(this List<string> items, int start,int end)
    {
        for (int i = start; i <= end; i++)
        {
            items.Add($"images{i}.png");
        }
    }
    public static string GetImageFileNameWithIndex(this List<string> items, int index)
    {
        return items[index];
    }
}

用法

private List<string> _imgImageitems = new List<string>();
private List<string> _btnImageitems = new List<string>();

private void InitializeImages()
{
    _imgImageitems.InitializeImageArray(1, 5);
    _btnImageitems.InitializeImageArray(6, 10);
}

获取带有索引的图像文件名

string image = _imgImageitems.GetImageFileNameWithIndex(1);

反向列表

_imgImageitems.Reverse();

答案 1 :(得分:1)

您的图片在哪里?在您项目的文件夹中?如果是这样,您可以执行以下操作以获取所有图像文件名:

// Get the path to the app's Assets folder.
string root = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
string path = root + @"\Assets";  // where your image files are located

// Get the folder object that corresponds to this absolute path in the file system.
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(path);

IReadOnlyList<StorageFile> items = await folder.GetFilesAsync();

List<string> listOfNames = items.Select(x=>x.Name).ToList();
//or you can leave it as IEnumerable... or you can convert ToArray()