c#-自定义类型Convert.ToString
使用我创建的自定义类型的c#-自定义类型Convert.ToString,c#,asp.net,asp.net-mvc,razor,C#,Asp.net,Asp.net Mvc,Razor,使用我创建的自定义类型的@Html.TextBoxFor呈现文本框时遇到问题。我的自定义类型如下所示: public class Encrypted<T> { private readonly Lazy<T> _decrypted; private readonly Lazy<string> _encrypted; public static implicit operator Encrypted<T>(T value)
@Html.TextBoxFor
呈现文本框时遇到问题。我的自定义类型如下所示:
public class Encrypted<T>
{
private readonly Lazy<T> _decrypted;
private readonly Lazy<string> _encrypted;
public static implicit operator Encrypted<T>(T value)
{
return new Encrypted<T>(value);
}
public static implicit operator string(Encrypted<T> value)
{
return value._encrypted.Value;
}
...
}
在我看来,我有一个标准的@Html.TextBoxFor(m=>m.Name)
。但是,当呈现时,我的文本框的值设置为:Services.Encrypted`1[System.String]`
这大概是因为我使用的是自定义类型,而编译器不知道如何将我的类型转换为字符串值
我尝试使用自定义的类型转换器
:
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
var encrypted = value as IEncrypted;
if (encrypted != null)
{
return encrypted.DecryptedValue();
}
}
return null;
}
然后在我的加密模型上,我添加了:
[TypeConverter(typeof(EncryptedTypeConveter))]
但是,它似乎没有使用自定义的
类型转换器
。有人知道我如何解决这个问题吗?你需要覆盖ToString()
你好,谢谢你的评论。我已经重写了ToString()
方法-我已经更新了我的原始帖子,以包含代码片段。@Scrooby当您使用new
关键字时,您实际上并没有重写ToString方法;这就是所谓的“隐藏”。要覆盖,你必须使用覆盖关键字。@Wily博士的徒弟-你完全正确。那是一个真正的掌心时刻。谢谢
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
var encrypted = value as IEncrypted;
if (encrypted != null)
{
return encrypted.DecryptedValue();
}
}
return null;
}
[TypeConverter(typeof(EncryptedTypeConveter))]