[英]When is a specific type actually a System.Object?
In my WPF application, I have the following bit of code in an IValueConverter: 在我的WPF应用程序中,我在IValueConverter中具有以下代码:
if (value.GetType().BaseType != typeof(Member))
return string.Empty;
Member
is an auto-generated Entity Framework object. Member
是一个自动生成的实体框架对象。 When bound to a property of List<Member>
it works as expected - the converter accepts this comparison and does not return. 当绑定到
List<Member>
的属性时,它将按预期工作-转换器接受此比较,并且不返回。
I'm currently writing some unit tests for this part of the code. 我目前正在为这部分代码编写一些单元测试。 So I tested it with this:
因此,我对此进行了测试:
MemberConverter conv = new MemberConverter();
Member mem = new Member{ MemberName = "Arnold" };
var result = conv.Convert((Member)mem, typeof(string), null, null);
And result
comes back as String.Empty
. result
返回为String.Empty
。
When I step through the code, it's the type comparison that's failing. 当我单步执行代码时,类型比较失败了。 My self-generated
mem
object has a BaseType
of System.Object
. 我自己生成的
mem
对象的BaseType
为System.Object
。
I can understand why the base type could come back has a plain old object. 我能理解为什么基类型可能会返回一个普通的旧对象。 But I can't see why it's behaving differently in these two scenarios.
但是我看不出为什么在这两种情况下它的表现有所不同。 Can someone explain, and tell me what I'm doing wrong?
有人可以解释一下,告诉我我在做什么错吗?
Entity Framework is creating a dynamic type on the fly that has Member as a base type, overridding any virtual properties you supply to provide automatic 'lazy loading' magic. 实体框架正在动态创建一个以成员为基本类型的动态类型,该动态类型会覆盖您提供的任何虚拟属性以提供自动的“延迟加载”魔术。
You might consider doing this instead: 您可以考虑这样做:
if (!typeof(Member).IsAssignableFrom(value.GetType()))
Or, even more directly, since you have an instance and not just a type 或者,甚至更直接地,因为您有一个实例而不仅仅是一个类型
if (!(value is Member))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.