简体   繁体   English

检索自定义属性中的属性值

[英]Retrieving a Property Value Inside a Custom Attribute

Right now I have an attribute called Checkbox. 现在我有一个名为Checkbox的属性。 We're using it because of our front end posts "On" and "Off" instead of true/false when a checkbox value is submitted. 我们正在使用它,因为我们的前端帖子“On”和“Off”而不是true / false,当提交复选框值时。

Our goal is to parse the on/off values and convert them to true/false before they get to the JSON converter, so they can be picked up as a boolean. 我们的目标是解析开/关值并在它们到达JSON转换器之前将它们转换为true / false,这样它们就可以被选为布尔值。

I've considered using this attribute to handle that. 我考虑过使用这个属性来处理它。

    [Checkbox]
    [JsonConverter(typeof(InvariantConverter))]
    public bool CheckboxInputValue { get; set; }

I need access to the value of the property inside of the checkbox attribute and then need the ability to modify the value. 我需要访问checkbox属性中的属性值,然后需要能够修改该值。

Open to suggestions and thoughts here. 在这里接受建议和想法。

You cannot store per-instance data in an attribute property since the attribute is created when using the reflection API on the class. 您不能将每个实例数据存储在属性属性中,因为在类上使用反射API时会创建该属性。

You should rather use a custom JSON converter to convert between the string values and the boolean value. 您应该使用自定义JSON转换器在字符串值和布尔值之间进行转换。

As Martin Ullrich already suggested you should consider using a dedicated JSON converter. 正如Martin Ullrich已经建议你应该考虑使用专用的JSON转换器。

I left null value handling for you. 我为你留下了空值处理。

public class OnOffStringToBoolConverter : JsonConverter
{
    private readonly Type _sourceType = typeof(string);
    private readonly Type _targetType = typeof(bool);

    public OnOffStringToBoolConverter()
    {

    }

    public override bool CanRead => true;

    public override bool CanWrite => true;

    public override bool CanConvert(Type objectType)
    {
        if (objectType == null)
        {
            throw new ArgumentNullException(nameof(objectType));
        }

        return objectType == _sourceType;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader == null)
        {
            throw new ArgumentNullException(nameof(reader));
        }

        if (objectType == null)
        {
            throw new ArgumentNullException(nameof(objectType));
        }

        if (serializer == null)
        {
            throw new ArgumentNullException(nameof(serializer));
        }

        if (reader.Value == null)
        {
            // Add some null handling logic here if needed.
            throw new JsonSerializationException(
                $"Unable to deserialize null value to {_targetType.Name}.");
        }

        if (string.Compare(reader.Value.ToString(), "On", StringComparison.OrdinalIgnoreCase) == 0)
        {
            return true;
        }

        if (string.Compare(reader.Value.ToString(), "Off", StringComparison.OrdinalIgnoreCase) == 0)
        {
            return false;
        }

        throw new JsonSerializationException(
            $"Unable to deserialize '{reader.Value}' to {_targetType.FullName}. " +
            $"This converter supports only \"On\", \"Off\" values.");

    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (writer == null)
        {
            throw new ArgumentNullException(nameof(writer));
        }

        if (serializer == null)
        {
            throw new ArgumentNullException(nameof(serializer));
        }

        if (value == null)
        {
            // Add some null handling logic here if needed.
            throw new JsonSerializationException("Unable to serialize null value.");
        }

        // Write value only if it is boolean type.
        if (value is bool boolValue)
        {
            writer.WriteValue(boolValue ? "On" : "Off");
        }
        else
        {
            throw new JsonSerializationException(
                $"Unable to serialize '{value}' of type {value.GetType().FullName}. " +
                $"This converter supports deserialization of values " +
                $"of {_targetType.FullName} type only.");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM