【发布时间】:2012-04-24 18:04:17
【问题描述】:
如何使用反射仅获取基类中的属性,而不是继承的类。
假设我的基类有一个虚方法,而继承类覆盖了它。如果覆盖调用 base.MyMethod() 则 base.MyMethod() 中的反射从两个类或仅继承类获取属性,具体取决于使用的 BindingFlags。
有没有办法只能访问基类中的属性?
编辑:也许一些代码可以帮助解释我为什么要这样做。
internal static void Save(DataTransactionAccess data, string sproc, object obj)
{
if (checkMandatoryProperties(obj))
{
saveToDatabase(data, sproc, obj);
}
}
private static void saveToDatabase(DataTransactionAccess data, string sproc, object obj)
{
List<object> paramList;
PropertyInfo idProperty;
populateSaveParams(out paramList, out idProperty, obj);
if (idProperty != null)
{
int id = data.ExecuteINTProcedure(sproc, paramList.ToArray());
idProperty.SetValue(obj, id, null);
}
else
{
data.ExecuteProcedure(sproc, paramList.ToArray());
}
}
private static void populateSaveParams(out List<object> paramList, out PropertyInfo idProperty, object obj)
{
paramList = new List<object>();
idProperty = null;
foreach (PropertyInfo info in obj.GetType().GetProperties())
{
if (info.GetCustomAttributes(typeof(SaveProperty), true).Length > 0)
{
paramList.Add("@" + info.Name);
paramList.Add(info.GetValue(obj, null));
}
if (info.GetCustomAttributes(typeof(SaveReturnIDProperty), true).Length > 0)
{
idProperty = info;
}
}
}
在 populateSaveParams 的 foreach 循环中,我需要获取调用 Save 的 obj 中的类的属性,而不是它继承自的任何类或其任何子类。
希望这能让它更清楚。
【问题讨论】:
-
在检查值时您使用的是
GetType还是typeof(BaseClass)?我认为后者只会得到你的基类值。 -
我不能使用 typeof(BaseClass) 因为这是一个接口的扩展方法,所以需要在运行时使用 GetType() 确定底层类。
-
如果你的扩展方法只知道接口,为什么还要关心基类呢?听起来你的扩展方法太宽泛了。
-
扩展方法创建对保存存储过程的调用,具体取决于用自定义属性修饰的属性。通常这可以正常工作,但我要求类的层次结构有自己的存储过程,并且只保存在要考虑的各个类中声明的属性。
-
所以类型层次结构中的每个单独类型都有自己的保存步骤?
标签: c#