我们的域模型中使用了自定义的LocalizedString类型。我们要装饰具有验证属性的属性,如MaxLength
。为此,我们添加了隐式运算符以启用此属性所需的强制转换。未通过属性调用的隐式/显式转换运算符(System.ComponentModel.DataAnnotation.dll)
奇怪的是,运算符似乎永远不会被调用,并且在属性IsValid
方法中抛出InvalidCastException get。在我们自己的项目中进行演员制作。
是否有一个特殊的强制性行为编译器magix在这个系统中执行clr ngen'ed属性或者什么?
// Custom type
public class LocalizedString
{
public string Value
{
get { return string.Empty; }
}
public static implicit operator Array(LocalizedString localizedString)
{
if (localizedString.Value == null)
{
return new char[0];
}
return localizedString.Value.ToCharArray();
}
}
// Type: System.ComponentModel.DataAnnotations.MaxLengthAttribute
// Assembly: System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.ComponentModel.DataAnnotations.dll
public override bool IsValid(object value)
{
this.EnsureLegalLengths();
if (value == null)
{
return true;
}
else
{
string str = value as string;
int num = str == null ? ((Array) value).Length : str.Length;
if (-1 != this.Length)
return num <= this.Length;
else
return true;
}
}
[TestMethod]
public void CanCallIsValidWithLocalizedString()
{
// Arrange
var attribute = new MaxLengthAttribute(20);
var localized = new LocalizedString { Value = "123456789" };
// Act
var valid = attribute.IsValid(localized);
// Assert
Assert.IsFalse(valid);
}
感谢您的帮助。
编辑
Das Objekt des Typs "Nexplore.ReSearch.Base.Core.Domain.Model.LocalizedString" kann nicht in Typ "System.Array" umgewandelt werden.
bei System.ComponentModel.DataAnnotations.MaxLengthAttribute.IsValid(Object value)
bei Nexplore.ReSearch.Base.Tests.Unit.Infrastructure.CodeFirst.MaxLengthLocalizedAttributeTests.CanCallIsValidWithLocalizedString() in d:\Nexplore\SourceForge\Nexplore.ReSearch.Base\Source\Nexplore.ReSearch.Base.Tests.Unit\Infrastructure.CodeFirst\MaxLengthLocalizedAttributeTests.cs:Zeile 40.
+1我必须读两遍,直到我看到“这是一个类型检查”!所以将未知类型的对象转换为其他类型的唯一方法是使用IConvertible? –
@Adriano我不确定我会过度倾向于'IConvertible',但确实是*类似的东西,是的 –
谢谢,现在很多其他的东西变得清晰了! :-O –