C#在运行时创建属性

时间:2015-03-17 19:42:04

标签: c#

我有一个包含一些声音文件的文件夹。我想要做的是,在运行时,用一个完整的路径和文件名填充一个类(SoundFileNames.c)。我希望它是这样的,如果我在所述文件夹中有文件“MySound.wav”,我可以像这样索引它:SoundFileNames.MySound,它将产生C:.. \ MySound.wav。 我不知道这是否是最好的解决方案,甚至可能。我怎样才能做到这一点?任何帮助都很受欢迎。

由于

1 个答案:

答案 0 :(得分:0)

这是一个简单的SoundPathProvider,您可以将其用作模板以达到所需的行为。

using System;
using System.IO;
using System.Linq;

namespace SoundProvider
{
    public class SoundPathProvider
    {
        private readonly string _sourcePath;

        public SoundPathProvider(string sourcePath)
        {
            _sourcePath = sourcePath;
        }

        public string GetSoundPath(string soundName)
        {
            var files = Directory.EnumerateFiles(_sourcePath);
            var targetSound = files.FirstOrDefault(x => x.Split('\\').Last() == soundName);
            if (targetSound != null)
                return Path.Combine(_sourcePath, soundName);
            else 
                throw new Exception(string.Format("Sound '{0}' Not Found in '{1}'", soundName, _sourcePath));
        }
    }
}

模板单元测试可以帮助您开发功能。

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace SoundProvider
{
    [TestClass]
    public class SoundPathProviderTests
    {
        [ExpectedException(typeof(Exception))]
        [TestMethod]
        public void SoundPathProvider_GetNonExistentSoundPath_ThrowsException()
        {
            var provider = new SoundPathProvider("C:\\Temp\\SoundProviderSource");

            var soundPath = provider.GetSoundPath("NonExistentSound.wav");
        }

        [TestMethod]
        public void SoundPathProvider_GetExistingSoundPath_ThrowsException()
        {
            var provider = new SoundPathProvider("C:\\Temp\\SoundProviderSource");

            var soundPath = provider.GetSoundPath("SampleSound.wav");

            Assert.AreEqual("C:\\Temp\\SoundProviderSource\\SampleSound.wav", soundPath);
        }
    }
}