当我声明以下简单类时:
class Class1<T>
{
protected virtual T Prop1 { get; set; }
protected virtual string Prop2 { get; set; }
}
class Class2 : Class1<string>
{
protected override string Prop1 { get; set; }
protected override string Prop2 { get; set; }
}
现在我使用反射来获取 Class2 的属性,如下所示:
var hProperties = typeof(Class2).GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);
那么 Prop2 将被列出一次,而 Prop1 将被列出两次!这种行为对我来说似乎很奇怪。 Prop1 和 Prop2 不应该被视为相同吗??
如何才能在 hProperties 中只拥有 Prop1 一次?我不想使用 BindingFlags.DeclaredOnly,因为我还想获得 Class1 的其他未被覆盖的 protected 属性。
最佳答案
让我们看看编译后的程序集的元数据,以确保这两个属性除了名称之外具有相同的结构:
我使用 ILDASM 而不是通常的反编译器工具来确保没有以更友好的方式隐藏或显示任何内容。除了名称之外,这两个属性完全相同。
两个之一Prop1返回的属性来自 Class1其中之一来自Class2 .
这似乎是一个错误。该错误似乎是基类成员未正确添加到结果中。当DeclaredOnly未指定 all inherited properties should be returned as well .
我正在使用 DotPeek 和 Reflector VS 扩展,它允许调试反编译的 BCL 代码来调试反射代码。在这个问题中看到的行为是在这个方法中触发的:
private void PopulateProperties(RuntimeType.RuntimeTypeCache.Filter filter, RuntimeType declaringType, Dictionary<string, List<RuntimePropertyInfo>> csPropertyInfos, bool[] usedSlots, ref RuntimeType.ListBuilder<RuntimePropertyInfo> list)
{
int token = RuntimeTypeHandle.GetToken(declaringType);
if (MetadataToken.IsNullToken(token))
return;
MetadataEnumResult result;
RuntimeTypeHandle.GetMetadataImport(declaringType).EnumProperties(token, out result);
RuntimeModule module = RuntimeTypeHandle.GetModule(declaringType);
int numVirtuals = RuntimeTypeHandle.GetNumVirtuals(declaringType);
for (int index1 = 0; index1 < result.Length; ++index1)
{
int num = result[index1];
if (filter.RequiresStringComparison())
{
if (ModuleHandle.ContainsPropertyMatchingHash(module, num, filter.GetHashToMatch()))
{
Utf8String name = declaringType.GetRuntimeModule().MetadataImport.GetName(num);
if (!filter.Match(name))
continue;
}
else
continue;
}
bool isPrivate;
RuntimePropertyInfo runtimePropertyInfo = new RuntimePropertyInfo(num, declaringType, this.m_runtimeTypeCache, out isPrivate);
if (usedSlots != null)
{
if (!(declaringType != this.ReflectedType) || !isPrivate)
{
MethodInfo methodInfo = runtimePropertyInfo.GetGetMethod();
if (methodInfo == (MethodInfo) null)
methodInfo = runtimePropertyInfo.GetSetMethod();
if (methodInfo != (MethodInfo) null)
{
int slot = RuntimeMethodHandle.GetSlot((IRuntimeMethodInfo) methodInfo);
if (slot < numVirtuals)
{
if (!usedSlots[slot])
usedSlots[slot] = true;
else
continue;
}
}
if (csPropertyInfos != null)
{
string name = runtimePropertyInfo.Name;
List<RuntimePropertyInfo> list1 = csPropertyInfos.GetValueOrDefault(name);
if (list1 == null)
{
list1 = new List<RuntimePropertyInfo>(1);
csPropertyInfos[name] = list1;
}
for (int index2 = 0; index2 < list1.Count; ++index2)
{
if (runtimePropertyInfo.EqualsSig(list1[index2]))
{
list1 = (List<RuntimePropertyInfo>) null;
break;
}
}
if (list1 != null)
list1.Add(runtimePropertyInfo);
else
continue;
}
else
{
bool flag = false;
for (int index2 = 0; index2 < list.Count; ++index2)
{
if (runtimePropertyInfo.EqualsSig(list[index2]))
{
flag = true;
break;
}
}
if (flag)
continue;
}
}
else
continue;
}
list.Add(runtimePropertyInfo);
}
}
为什么公共(public)属性的行为消失了?
if (!(declaringType != this.ReflectedType) || !isPrivate)
有一张支票。
Class1<string>.Prop2这里被过滤掉了:
bool flag = false;
for (int index2 = 0; index2 < list.Count; ++index2)
{
if (runtimePropertyInfo.EqualsSig(list[index2]))
{
flag = true;
break;
}
}
if (flag)
continue;
因为EqualsSig返回真。如果您要求私有(private)成员,那么属性似乎会按名称和 sig 进行重复数据删除......我不知道为什么。不过,似乎是故意的。
遵循这些令人费解的代码很累人。 This is better and commented.我怀疑他们正在删除私有(private)属性,因为您可以通过从某个类继承以获取它的所有私有(private)成员来提升特权。
答案如下:
// For backward compatibility, even if the vtable slots don't match, we will still treat
// a property as duplicate if the names and signatures match.
因此他们添加了一个 hack 以实现向后兼容性。
您必须添加自己的处理才能获得所需的行为。也许,Fastreflect可以提供帮助。
关于c# - 为什么 GetProperties 两次列出 protected 属性(在通用基类中声明)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24676479/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah
它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput
我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串