我有一个像这样的Helper方法来获取PropertyName(试图避免使用魔法字符串)publicstaticstringGetPropertyName(Expression>expression){varbody=(MemberExpression)expression.Body;returnbody.Member.Name;}但是有时我的PropertyNames也没有很好地命名。所以我宁愿使用DisplayAttribute。[Display(Name="LastName")]publicstringLastname{get;set;}请注意我使用的是Silverlight4.
这个问题在这里已经有了答案:C#:ListAllClassesinAssembly(2个答案)关闭9年前。如何使用反射列出当前项目(程序集?)中的所有类?谢谢。
我在单元测试中有以下代码publicboolTestMethodsOf(){varimpl=typeof(T);varvalid=true;foreach(varifaceinimpl.GetInterfaces().Where(i=>typeof(I).IsAssignableFrom(i))){varmembers=iface.GetMethods();foreach(varmemberinmembers){Trace.Write("Checkingifmethod"+iface.Name+"."+member.Name+"isvirtual...");varimplMember=
在C#中执行此操作的最佳方法是什么?stringpropPath="ShippingInfo.Address.Street";我将有一个属性路径,就像上面从映射文件中读取的那样。我需要能够询问Order对象下面代码的值是什么。this.ShippingInfo.Address.Street平衡性能与优雅。所有对象图关系都应该是一对一的。第2部分:如果它是List或类似的东西,添加它获取第一个的能力有多难。 最佳答案 也许是这样的?stringpropPath="ShippingInfo.Address.Street";objectp
我通过反射调查了2个接口(interface)和2个类:家长IChild-派生自IParent家长子级-派生自父级对我来说奇怪的是,当我通过对IChild类型的反射进行查看时,我没有找到IParent方法。应用于Child类型的相同代码按预期工作-反射显示Parent方法。interfaceIParent{voidParentMethod();}interfaceIChild:IParent{voidChildMethod();}classParent{publicvoidParentMethod(){}}classChild:Parent{publicvoidChildMethod(
我正在为一个类构造函数编写一些代码,它循环遍历该类的所有属性并调用一个通用静态方法,该方法使用来自外部API的数据填充我的类。所以我把它作为一个示例类:publicclassMyClass{publicstringProperty1{get;set;}publicintProperty2{get;set;}publicboolProperty3{get;set;}publicstaticTDoStuff(stringname){//getthedataforthepropertyfromtheexternalAPI//orifthere'saproblemreturn'default(
usingSystem;usingSystem.Reflection;namespaceReflection{classTest{protectedvoidmethodname(inti){Console.WriteLine(("intheworldofthereflection-onlyi"));Console.Read();}protectedvoidmethodname(inti,intj){Console.WriteLine(("intheworldofthereflectioni,j"));Console.Read();}}classProgram{staticvoidMai
如果我有一个像这样的LINQ语句x=Table.SingleOrDefault(o=>o.id==1).o.name;如何使用反射将传入的变量替换为“id”和“name”?当我尝试时,我不断收到对象引用未设置为对象错误的实例。我的尝试是这样的x=(string)Table.SingleOrDefault(o=>(int?)o.GetType().GetProperty(idString).GetValue(o,null)==1).GetType().GetField(nameString).GetValue(x);任何帮助都会很棒。谢谢。 最佳答案
我需要使用反射来检索NullableTypeofDateTime的属性值我该怎么做?当我尝试propertyInfo.GetValue(object,null)时,它不起作用。谢谢我的代码:varpropertyInfos=myClass.GetType().GetProperties();foreach(PropertyInfopropertyInfoinpropertyInfos){objectpropertyValue=propertyInfo.GetValue(myClass,null);}对于可为null的类型,propertyValue结果始终为null
我尝试动态设置一个Nullable属性。我得到我的属性(property)ex:PropertyInfoproperty=class.GetProperty("PropertyName");//MypropertyisNullableatthistimeSothetypecouldbeastringorint我想像这样通过反射来设置我的属性property.SetValue(class,"1256",null);当我的属性是NullableGeneric时它不起作用。所以我试图找到一种方法来设置我的属性。了解我执行的可空属性的类型Nullable.GetUnderlyingType(p