I have a model called 'Entity' which implements 'IEntity' interface as follows (simplified):
public interface IEntity<T> where T : IComparable
{
T Id { get; set; }
}
public class Entity: IEntity<Guid>
{
public Guid Id { get; set; }
public Guid LayoutId { get; set; }
public virtual Layout Layout {get; set;}
}
I would like to clone an object of this 'Entity' model while ignoring virtual properties as follows:
public static class CloneHelper
{
public static T CloneNonVirtual<T>(this T source) where T : class
{
var cloneObj = Activator.CreateInstance<T>();
foreach (var prop in source.GetType().GetProperties().Where(w => w.CanWrite && !w.GetAccessors().Any(x => x.IsVirtual)))
{
var cloneObjProp = cloneObj.GetType().GetProperty(prop.Name);
cloneObjProp.SetValue(cloneObj, prop.GetValue(source));
}
return cloneObj;
}
}
Here, the problem is that LayoutId's accessors are not virtual, but Id's accessors are! Please see both QuickWatch windows:
Why does this occur? Is this because Id is an implemented property of the generic interface 'IEntity'? If so and if this is intended behavior, why?
Thanks,
Ferit
Aucun commentaire:
Enregistrer un commentaire