c# - 类属性的 TypeConverter 用法
问题描述
我有一个类EntityItemValue
,它的属性名为Value
type object
,实际类型可以通过位于类Type
内部的属性来确定EntityItem
。
public class EntityItemValue
{
public EntityItem Item { get; set; }
public object Value { get; set; }
// other properties ...
}
public class EntityItem
{
public Type Type
// other properties ...
}
现在我想像Value
下面这样绑定 Blazor 组件中的属性。
<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”应用于类型以注册转换器。
我了解这里的问题是什么,但是如何根据类中的属性TypeConverter
正确使用任何实现想法或更好的建议来解决这个问题?Type
EntityItem
解决方案
由于<input>
元素只绑定到字符串 - 我们可以在设置参数时首先检查:
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" />
推荐阅读
- scala - 在 Json 层次结构中查找包含值的分支
- qt - How to make a table scrollbar look the same in both windows and mac
- windows - 在不捆绑 JS 文件的情况下运行 Kibana
- svn - A 不知道存在于存储库中并且不是提交的一部分,但它的子 B 是提交的一部分
- apiconnect-test-monitor - 在 IBM API Connect Test and Monitor 中设置授权标头
- r - 使用汇总(或等效?)在 R 数据框中创建一列函数
- javascript - 在此示例中,如何更改单击时的图标?
- python - 多行搜索和替换
- javascript - 每个 Google Apps 脚本都会导致错误,但不会
- python - 如何获取数据框每一行中特定值的列名