如何检查状态对象是否属于 ICollection 类型
How to check if a state object is of type ICollection
我使用 nhibernate 拦截器来比较实体属性的旧状态和当前状态的值,但是一些属性的类型是 ICollection
所以谁能指导我如何检查一个对象类型为 ICollection
这是我的代码
public void OnPostUpdate(NHibernate.Event.PostUpdateEvent @event)
{
var entityToAudit = @event.Entity as IAuditable;
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AuditLog.txt");
using (StreamWriter sw = File.AppendText(path))
{
for (int i = 0; i < @event.OldState.Length; i++)
{
string propertyName = @event.Persister.PropertyNames[i];
if (@event.OldState[i] != null)
{
if (!@event.OldState[i].Equals(@event.State[i]))
{
sw.WriteLine("the value of "+ propertyName + " has been changed from " + @event.OldState[i] + " to " + @event.State[i]);
}
}
else
{
if (@event.State[i] != null)
{
sw.WriteLine("the value of "+ propertyName + " has been changed from being empty to " + @event.State[i]);
}
}
}
}
}
您可以使用简单的 is 检查类型
像这样:
var obj = getObject();
if(obj is TypeYouWant)
doSomething();
祝你好运
您有多个选项可以执行此操作,使用 is 或使用 as 进行空值检查:
if (obj is ICollection){
//your logic
}
或者,如果您稍后需要对象作为 ICollection,我建议使用 as:
var icoll = obj as ICollection
if (icoll != null){
//use icoll
//icoll.Something();
}
我使用 nhibernate 拦截器来比较实体属性的旧状态和当前状态的值,但是一些属性的类型是 ICollection
所以谁能指导我如何检查一个对象类型为 ICollection
这是我的代码
public void OnPostUpdate(NHibernate.Event.PostUpdateEvent @event)
{
var entityToAudit = @event.Entity as IAuditable;
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AuditLog.txt");
using (StreamWriter sw = File.AppendText(path))
{
for (int i = 0; i < @event.OldState.Length; i++)
{
string propertyName = @event.Persister.PropertyNames[i];
if (@event.OldState[i] != null)
{
if (!@event.OldState[i].Equals(@event.State[i]))
{
sw.WriteLine("the value of "+ propertyName + " has been changed from " + @event.OldState[i] + " to " + @event.State[i]);
}
}
else
{
if (@event.State[i] != null)
{
sw.WriteLine("the value of "+ propertyName + " has been changed from being empty to " + @event.State[i]);
}
}
}
}
}
您可以使用简单的 is 检查类型 像这样:
var obj = getObject();
if(obj is TypeYouWant)
doSomething();
祝你好运
您有多个选项可以执行此操作,使用 is 或使用 as 进行空值检查:
if (obj is ICollection){
//your logic
}
或者,如果您稍后需要对象作为 ICollection,我建议使用 as:
var icoll = obj as ICollection
if (icoll != null){
//use icoll
//icoll.Something();
}