使用数据类型作为字典中的值

时间:2015-03-16 17:01:05

标签: c# dictionary

我有这种结构 - 这里是一个虚拟实现:

interface IBasicWaveform
{
    double FindAmplitudeFactor(int samplesPerSecond);
    double ValueAtPhase(double phase);
}

abstract class BaseWaveform : IBasicWaveform
{
    public double FindAmplitudeFactor(int samplesPerSecond)
    {
        throw new NotImplementedException();
    }

    public double ValueAtPhase(double phase)
    {
        throw new NotImplementedException();
    }
}

sealed class SawDownWaveform : BaseWaveform
{
}

sealed class SawUpWaveform : BaseWaveform
{
}

我想创建一个带有Description(字符串)和BaseWaveform DATA TYPE作为TValue的Dictionary

所以我想写这样的代码:

    var myDict = new Dictionary<string,  BaseWaveform**Datatype** >()
    {
        {"Saw down", SawDownWaveform},
        {"Saw up", SawUpWaveform}
    }

我也试过这个:

    var myDict = new Dictionary<string, Type>()    
    {
        {"Saw down", (Type)SawDownWaveform},
        {"Saw up", (Type)SawUpWaveform}
    };

但它给了我一个编译错误:

  

'WindowsFormsApplication5.SawDownWaveform'是'type',但用作'变量'

问题是:我怎样才能在c#中做到这一点?

2 个答案:

答案 0 :(得分:2)

typeof运算符是在编译时给出类型标识符时获取Type对象的方式:

var myDict = new Dictionary<string, Type>()    
{
    {"Saw down", typeof(SawDownWaveform)},
    {"Saw up", typeof(SawUpWaveform)}
};

答案 1 :(得分:1)

我相信您只是想使用typeof()运算符而不是尝试转换为(Type)

var myDict = new Dictionary<string, Type>()    
{
    {"Saw down", typeof(SawDownWaveform)},
    {"Saw up", typeof(SawUpWaveform)}
};