将枚举映射到 json 属性

我有一个名为 InstrumentConfigValues 的类,其属性具有实现接口的类型。现在我有一个名称为 InstrumentConfig 的枚举,它具有一组值。这些值类似于 json 文件中的键。我想映射类似 .[JsonProperty(InstrumentConfig.LowDiskpace.ToString()]


由于某种原因,它不允许这样做,并抱怨说:


属性参数必须是常量表达式


我提到了许多专门针对JsonStringEnumConverter的帖子。但是,如何使用枚举键映射每个属性。我还看到了这篇文章JsonSerializationSettings,但无法与我的问题相关联。请帮忙/


public class InstrumentConfigValues : IInstrumentConfig

{      

    public double SpaceNeededForSingleRun

    {

        get; set;

    }


    public int NumberOfInputSlots

    {

        get; set;

    }


    public int SupportedChannelCount

    {

        get; set;

    }

}


//I want this inheritance as some other class wants to access the values.

public abstract class InstrumentConfigReadWrite : InstrumentConfigValues

{

    protected ReturnCodes PopulateValuesFromJObject(JObject jObject, string path)

    {

        try

        {

            if (JsonConvert.DeserializeObject<InstrumentConfigValues>(jObject.ToString()) == null)

            {

                return ReturnCodes.ErrorReadingFile;

            }

        }

        catch (JsonSerializationException jex)

        {

            SystemDebugLogLogger.LogException(jex, "Invalid Instrument Config File Values. Data needs to be copied over.");

            return ReturnCodes.ErrorReadingFile;

        }

        return ReturnCodes.Success;

    }

}


白猪掌柜的
浏览 61回答 1
1回答

倚天杖

只要您使用的是当前编译器,就可以使用&nbsp;nameof。[JsonProperty(nameof(InstrumentConfig.LowDiskpace))]如果您尝试使用它,并收到类似 的错误,则表示您没有使用当前的编译器。关键字是在 C# 6.0/Visual Studio 2015 中引入的 - 任何比这更新的关键字都应该没问题。Compilation error: The name 'nameof' does not exist in the current contextnameof
打开App,查看更多内容
随时随地看视频慕课网APP