逻辑循环,
问题描述:
我很书面方式小乐的应用程序和我玩每88个键是这样的:逻辑循环,
if (nutka == "A0" && msg.Velocity < 28)
{
PlayEngine.Instance.PlaySound("-12dB_01");
}
else if (nutka == "A0" && msg.Velocity < 55 && msg.Velocity > 27)
{
PlayEngine.Instance.PlaySound("-9dB_01");
}
else if (nutka == "A0" && msg.Velocity < 82 && msg.Velocity > 54)
{
PlayEngine.Instance.PlaySound("-6dB_01");
}
else if (nutka == "A0" && msg.Velocity < 106 && msg.Velocity > 81)
{
PlayEngine.Instance.PlaySound("-3dB_01");
}
else if (nutka == "A0" && msg.Velocity < 128 && msg.Velocity > 105)
{
PlayEngine.Instance.PlaySound("0dB_01");
}
正如你所看到的,我有5个速度范围为信号的一个关键,从我的外部MIDI控制器。而且我有类似的88如果说明,唯一的变化就是:“nutka”的名称和播放文件名称中的最后一位数字
(例如,在这里我们可以使用一个音符“A0” 5个文件取决于速度:-12dB_01,-9dB_01,-6dB_01,-3dB_01和0dB_01,这看起来真的很糟糕的代码为88音符...
不知道如何使短版或短循环。 ..任何帮助apprreciated。
答
也许你可以concatinate字符串:
var keys = new Dictionary<string, string>();
// fill dictionary with relations: A0 -> 01
keys.Add("A0", "01");
var key = keys[nutka];
int velocity;
if (msg.Velocity < 28)
velocity = -12
else if (msg.Velocity < 55)
velocity = -9
else if (msg.Velocity < 82)
velocity = -6
else if (msg.Velocity < 106)
velocity = -3
else
velocity = 0;
string tune = String.Format("{0}dB_{1}", velocity, key);
PlayEngine.Instance.PlaySound(tune);
字典的填充可以完成一次。
答
您通常由具有描述你的功能项目的列表做到这一点。
例如,给出一个简单的类
public class SoundInfo
{
public string Nutka{get;set;}
public int MinVelocity {get;set;}
public int MaxVelocity {get;set;}
public string SoundFile{get;set;}
}
你把它们存储在一个List<SoundInfo>
public List<SoundInfo> sounds
= new List<SoundInfo>()
{
new SoundInfo { Nutka = "A0", MinVelocity = 0, MaxVelocity = 28, SoundFile="-12dB_01" },
new SoundInfo { Nutka = "A0", MinVelocity = 28, MaxVelocity = 55 SoundFile="-6dB_01" },
new SoundInfo { Nutka = "A0", MinVelocity = 55, MaxVelocity = 82, SoundFile="-3dB_01" },
};
然后,您可以简单地查找正确的记录基础上,nutka
和msg.Velocity
值:
var item = sounds.SingleOrDefault(s => s.Nutka == nutka
&& msg.Velocity < s.MaxVelocity && msg.Velocity >= s.MinVelocity);
if(item == null)
throw new Exception ("No sound found!!");
PlayEngine.Instance.PlaySound(item.SoundFile);
+0
谢谢Jamiec它看起来是最好的方式,使其工作,看起来“更短”:) 穆罕默德Zeeshan - 这种方式我需要再做出每个音符A0,A1,B0,B1的另外87个声明.... ... – Martin
列表和和一些lamdas将成为你的朋友在这里! – Sean
如果'nutka ==“A1”'或'nutka ==“B4”'会怎么样?你能*计算最终的字符串吗? –