本文介绍了无法从基础转换为派生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在阅读一本关于NHibernate的书,并在单元测试中遇到了一个演员问题。这是问题所在:
I'm going through a book on NHibernate and have run into a casting issue in a unit test. Here's the issue:
public class Base
{
}
public class Derived : Base
{
public string property1 { get; set; }
}
public class Derived1 : Base
{
public string property1 { get; set; }
public string property2 { get; set; }
}
public class Derived2 : Base
{
public string property1 { get; set; }
public string property2 { get; set; }
public string property3 { get; set; }
}
public void TestDerived( )
{
object id = 0;
using( var transaction = session.BeginTransaction( ) )
{
id = session.Save( new OtherClassWithCollectionOfBase
{
Number = "123456789",
CollectionOfBase = new HashSet<Base>
{
new Derived
{
property1 = "value"
},
new Derived1
{
property1 = "value",
property2 = "value2"
},
new Derived2
{
property1 = "value",
property2 = "value2",
property3 = "value3",
}
}
} );
transaction.Commit( );
}
session.Clear( );
using( var transaction = session.BeginTransaction( ) )
{
var otherclass = session.Get<OtherClassWithCollectionOfBase>( id );
Assert.That( otherclass.CollectionOfBase.Count, Is.EqualTo( 3 ) );
var derived = otherclass.CollectionOfBase.OfType<Derived>( ).FirstOrDefault( );
Assert.That( derived, Is.Not.Null );
transaction.Commit( );
}
此断言与 derived == null。我也试过
This asserts with derived == null. I've also tried
var derived = otherclass as Derived;
和
var derived= otherclass.CollectionOfBase.FirstOrDefault(b => b.GetType() == typeof (Derived));
我已经尝试对集合的每个成员进行硬转换,并获得预期的结果NullReferenceException。这可能没有完成,或者我在代码中做错了什么?
I've tried a hard cast on each member of the collection with the expected result NullReferenceException. Can this just not be done or have I done something wrong in the code?
推荐答案
var obj = otherclass.CollectionOfBase.First();
var type = obj.GetType();
var typeName = type.FullName;
这篇关于无法从基础转换为派生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!