簡體   English   中英

c# - 自定義類型Convert.ToString

[英]c# - Custom type Convert.ToString

使用我創建的自定義類型使用@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;
    }

    ...
}

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

public class ExampleModel
{
    public Encrypted<string> Name { get; set; }
}

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

public ActionResult Index()
{
    var model = new ExampleModel
    {
        Name = "Example Name";
    };
    return View(model);
}

然后在我看來,我有標准的@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;
}

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

[TypeConverter(typeof(EncryptedTypeConveter))]

但它似乎沒有使用自定義TypeConverter 有誰知道我怎么解決這個問題?

您需要覆蓋ToString()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM