即使运算符重载也无法转换为字符串

时间:2012-02-16 20:17:14

标签: asp.net-mvc-3 c#-4.0 casting operator-overloading

在内部值为StringLength的{​​{1}}类型的属性上使用MVC3和MyType<string>验证属性,我得到一个例外:

  

无法将“MyType”类型的对象强制转换为“System.String”。

所以我添加了一个运算符重载,这是我的类:

string

理论上,这应该允许public class MyType<T> { public T Value { get; set; } //... public static implicit operator string(MyType<T> instance) { //Return the internal value of the instance. return Convert.ToString(instance.Value); } } 转换为MyType。但是,我仍然得到相同的错误,这里是堆栈跟踪:

  

[InvalidCastException:无法转换类型为“MyType”的对象进行输入   'System.String'。]
  System.ComponentModel.DataAnnotations.StringLengthAttribute.IsValid(对象   价值)+64
  System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(对象   value,ValidationContext validationContext)+176
  System.ComponentModel.DataAnnotations.ValidationAttribute.GetValidationResult(对象   value,ValidationContext validationContext)+41
  System.Web.Mvc.d__1.MoveNext()+267

String方法(来自.NET框架,而不是我的代码)正在执行此操作:

StringLengthAttribute.IsValid

似乎它应该有效,我缺少什么?

3 个答案:

答案 0 :(得分:1)

变量value声明为object类型。您必须首先转换为实际类型,因为基础对象不是string。没有从object定义到其他类型的转换,因此您正在进行的转换有效地告诉编译器该对象实际上是string。这与取消装箱值类型时必须遵循的规则基本相同。

首先将它转换为您的类型,编译器可以意识到从您的类型到所需的string类型存在(隐式)转换,并且可以生成相应的指令。

例如,

object obj = new MyObject<string> { Value = "Foobar" };
string x = (string)obj;           // fail: obj is not a string
string y = (MyObject<string>)obj; // obj: obj is cast to MyObject<string> and
                                  //      an implicit cast to string exists
// to be clearer
string z = (string)(MyObject<string>)obj;

答案 1 :(得分:0)

public override bool IsValid(object value)
{
    this.EnsureLegalLengths();
    int num = (value == null) ? 0 : ((MyType<string>)value).Value.Length;
    return value == null || (num >= this.MinimumLength && num <= this.MaximumLength);
}

请勿将其投放到string,而是投放到MyType<string>

反映这一点的更改代码行是:

    int num = (value == null) ? 0 : ((MyType<string>)value).Value.Length;

修改:请勿将MyType<string>传递给该方法,并将MyType<string>.Value传递给该方法,以便广告投放成功。

答案 2 :(得分:0)

您正在使用隐式转换,您应该进行显式转换,因为框架明确地转换它。像这样:

(string)value

你应该添加:

public static explicit operator string(MyType<T> instance)
{
    //Return the internal value of the instance.
    return Convert.ToString(instance.Value);
}