【发布时间】:2010-09-24 05:42:50
【问题描述】:
一些 C# 代码有一个奇怪的问题 - 属性的 Getter 方法在未显式标记时显示为虚拟。
该类的 DbKey 属性出现问题(完整代码):
public class ProcessingContextKey : BusinessEntityKey, IProcessingContextKey
{
public ProcessingContextKey()
{
// Nothing
}
public ProcessingContextKey(int dbKey)
{
this.mDbKey = dbKey;
}
public int DbKey
{
get { return this.mDbKey; }
set { this.mDbKey = value; }
}
private int mDbKey;
public override Type GetEntityType()
{
return typeof(IProcessingContextEntity);
}
}
当我使用反射检查 DbKey 属性时,我得到以下(意外)结果:
Type t = typeof(ProcessingContextKey);
PropertyInfo p = t.GetProperty("DbKey");
bool virtualGetter = p.GetGetMethod(true).IsVirtual; // True!
bool virtualSetter = p.GetSetMethod(true).IsVirtual; // False
为什么 virtualGetter 设置为 True?考虑到该属性既不是抽象也不是虚拟,我预计是错误的。
为了完整性 - 以及它们相关的远程可能性,这里是 BusinessEntityKey、IProcessingContextKey 和 IBusinessEntityKey 的声明:
public abstract class BusinessEntityKey : IBusinessEntityKey
{
public abstract Type GetEntityType();
}
public interface IProcessingContextKey : IBusinessEntityKey
{
int DbKey { get; }
}
public interface IBusinessEntityKey
{
Type GetEntityType();
}
提前感谢您的帮助。
澄清 - 为什么这对我很重要?
我们使用 NHibernate 并跟踪了一些延迟加载到只有一半可覆盖的属性的问题 - 虚拟 getter 但私有 setter。修复这些问题后,我们添加了一个单元测试来捕捉任何其他可能发生这种情况的地方:
public void RequirePropertiesToBeCompletelyVirtualOrNot()
{
var properties
= typeof(FsisBusinessEntity).Assembly
.GetExportedTypes()
.Where(type => type.IsClass)
.SelectMany(
type =>
type.GetProperties(
BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic))
.Where(property => property.CanRead
&& property.CanWrite)
.Where(property =>
property.GetGetMethod(true).IsVirtual
!= property.GetSetMethod(true).IsVirtual);
Assert.That(
properties.Count(),
Is.EqualTo(0),
properties.Aggregate(
"Found : ",
(m, p) => m + string.Format("{0}.{1}; ",
p.DeclaringType.Name,
p.Name)));
}
这个单元测试在上面提到的 DbKey 属性上失败了,我不明白为什么。
【问题讨论】:
-
附带问题,为什么会出现这个问题?
标签: c# .net reflection .net-3.5