c# - 自定义类型Convert.ToString

Dan*_*lis 3 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)
    {
        return new Encrypted<T>(value);
    }

    public static implicit operator string(Encrypted<T> value)
    {
        return value._encrypted.Value;
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

然后在我的模型上,我有:

public class ExampleModel
{
    public Encrypted<string> Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如果我手动填充控制器操作中的值:

public ActionResult Index()
{
    var model = new ExampleModel
    {
        Name = "Example Name";
    };
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

然后我认为我有标准@Html.TextBoxFor(m => m.Name).但是,当渲染时,我的文本框的值设置为:Services.Encrypted`1 [System.String]`

大概这是因为我使用的是自定义类型,编译器不知道如何将我的类型转换为字符串值.

我尝试过使用自定义TypeConverter:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后在我的加密模型上我添加了:

[TypeConverter(typeof(EncryptedTypeConveter))]
Run Code Online (Sandbox Code Playgroud)

但它似乎没有使用自定义TypeConverter.有谁知道我怎么解决这个问题?

SLa*_*aks 6

你需要覆盖ToString().