如何将变量强制转换为与动态变量相同的类型

本文关键字:变量 动态 类型 转换 | 更新日期: 2023-09-27 18:07:14

我目前正在研究一种放大方法,该方法接受PCM样本作为ICollection<dynamic>(调用者只会传递sbyte, shortint的集合)。我创建的放大算法工作得很好;只是我不确定如何将新放大的样本转换回其原始类型,因为放大逻辑将样本输出为List<double>

我知道我可以添加某种switch语句来将样本转换回其原始类型,但这似乎是一个相当原始的解决方案,是否有更好的方法来实现这一点?

我如何调用方法(samplesList<dynamic>包含int s, file是我为读取wav文件创建的类),

AmplifyPCM(samples, file.BitDepth, 0.5f);

我的方法,

static private List<dynamic> AmplifyPCM(ICollection<dynamic> samples, ushort bitDepth, float volumePercent)
{
    var highestSample = 0;
    var temp = new List<dynamic>();
    foreach (var sample in samples)
    {
        if (sample < 0)
        {
            temp.Add(-sample);
        }
        else
        {
            temp.Add(sample);
        }
    }
    foreach (var sample in temp)
    {
        if (sample > highestSample)
        {
            highestSample = sample;
        }
    }
    temp = null;
    var ratio = (volumePercent * (Math.Pow(2, bitDepth) / 2)) / highestSample; 
    var newSamples = new List<dynamic>();
    foreach (var sample in samples)
    {
        newSamples.Add(sample * ratio); // ratio is of type double, therefore implicit conversion from whatever sample's type is to a double.
    }
    // switch statement would go here if there's no better way.
    return newSamples;
}

如何将变量强制转换为与动态变量相同的类型

你可以让它泛型,它会给出返回类型。但是c#中不支持带有泛型的操作符。您可以尝试将它们设置为动态的。

static private List<T> AmplifyPCM<T>(ICollection<T> samples, ushort bitDepth, float volumePercent)
{
    var highestSample = 0;
    var temp = new List<T>();
    foreach (var sample in samples)
    {
        if ((dynamic)sample < 0)
        {
            temp.Add(-(dynamic)sample);
        }
        else
        {
            temp.Add(sample);
        }
    }
    foreach (var sample in temp)
    {
        if ((dynamic)sample > highestSample)
        {
            highestSample = (dynamic)sample;
        }
    }
    temp = null;
    var ratio = (volumePercent * (Math.Pow(2, bitDepth) / 2)) / highestSample;
    var newSamples = new List<T>();
    foreach (var sample in samples)
    {
        newSamples.Add((dynamic)(T)sample * ratio);
    }
    return newSamples;
}