【问题标题】:TypeConverter usage for class property类属性的 TypeConverter 用法
【发布时间】:2021-12-12 22:59:45
【问题描述】:

我有一个类EntityItemValue,它的属性名为Value,类型为object,实际类型可以通过位于EntityItem 类中的名为Type 的属性来确定。

public class EntityItemValue
{        
    public EntityItem Item { get; set; }
    public object Value { get; set; }
    // other properties ...
}

public class EntityItem
{        
    public Type Type
    // other properties ...
}

现在我想在 Blazor 组件中绑定 Value 属性,如下所示。

<div class="flex-container">
    <div class="input-style"><input type="text" @bind="@Param.Value" /></div>
</div>

@code {
    [Parameter]
    public EntityItemValue Param { get; set; }
}

但是得到这个异常:

类型“System.Object”没有关联的 TypeConverter 支持从字符串转换。将“TypeConverterAttribute”应用于类型以注册转换器。'

我了解这里的问题是什么,但是如何根据 EntityItem 类中的 Type 属性正确使用 TypeConverter 是否有任何实现想法的线索或解决此问题的更好建议?

【问题讨论】:

  • 为什么不使用字符串而不是对象?或者你之后的意图是什么?
  • @Alamakanambra,以前我使用字符串而不是对象,但在字符串表示中保存不同类型是一个问题,例如 DateTime 可以有不同的区域格式并且转换为 DateTime 是一个问题。我希望你明白这一点。

标签: c# asp.net-core blazor


【解决方案1】:

由于&lt;input&gt; 元素只绑定到字符串 - 我们可以在设置参数时首先检查:

protected override void OnParametersSet()
{
    if (Param.Item.Type != typeof(string))
    {
        throw new InvalidOperationException("Cannot bind a non string to a string input");
    }
}

现在我们有了这个,我们可以将object 包装成string

private string Value
{
    get => (string)Param.Value;
    set => Param.Value = value;
}

最后更新输入绑定到我们的字符串

<input type="text" @bind="@Value" />

【讨论】:

    猜你喜欢
    • 2012-12-05
    • 1970-01-01
    • 2020-10-28
    • 2015-09-28
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多