访问C#属性名或属性我想从类实例自动生成SQL语句。该方法应该类似于Update(object[]property,objectPrimaryKeyProperty)。该方法是实例的一部分(类、基方法-对任何子项都是通用的)。attribute_array是将在更新语句中使用的类属性数组。属性名称等于表字段名称。问题是我无法获取属性名称。是否有任何选项可以在类实例中获取属性名称?示例:publicclassMyClass{publicintiMyProperty{get;放;}公共字符串cMyProperty2{得到;放;}{main(){MyClass_main=newMyClass();_main.iMyProperty.*PropertyName*//应该返回字符串“iMyProperty”{我知道PropertyInfo,但我不知道如何从GetProperties()数组中获取属性的ID。有什么建议么?上周二为我们的用户组写了一篇关于lambda的演示文稿。代码:publicstaticclassMembersOf{publicstaticstringGetName(Expression>expr){varnode=expr.BodyasMemberExpression;if(object.ReferenceEquals(null,node))thrownewInvalidOperationException("Expressionmustbeofmemberaccess");返回node.Member.Name;我在这篇文章中找到了完美的解决方案publicstaticstringGetPropertyName(Expression>propertyExpression){return(propertyExpression.BodyasMemberExpression).Member.Name;然后使用:varpropertyName=GetPropertyName(()=>myObject.AProperty);//奇迹般地返回“AProperty”你可以这样做:Typet=someInstance.getType();foreach(MemberInfomiint.GetMembers()){if(mi.MemberType==MemberTypes.Property){Console.WriteLine(mi.Name);}}获取实例类型的所有属性名称。您可以使用PropertyInfo.Name来获取属性的名称(我假设这就是您所说的ID的意思)。只需遍历从typeof(className)返回的PropertyInfo[].GetProperties()foreach(PropertyInfoinfointypeof(MyClass).GetProperties()){stringname=info.Name;//usenamehere}由于您已经拥有所有Needanexplicithandletoaspecificproperty,所??以您知道名称-您只需要输入它吗?不能100%确定这是否会执行您想要的操作,这将获取您类中[Column]属性的所有属性:DataContext)).GetMetaType(typeof(TEntity)).DataMembers;}获取表列名称作为类中的属性:MyDataContextdb=GetDataContext();varallColumnPropertyNames=db.ColumnNames().Where(n=>n.Member.GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute),false).FirstOrDefault()!=null).Select(n=>n。姓名);让我们说(从第一个例子,类MyClass方法更新):publicclassMyClass{publicintiMyStatusProperty{get;放;}publicintiMyKey{得到;放;}publicintUpdateStatusProperty(intiValue){this.iMyStatusProperty=iValue;返回_Update(new[iMyStatusProperty],iMyKey);/这应该生成SQL:“UPDATEMyClasssetiMyStatusProperty={iMyStatusProperty}whereiMyKey={iMyKey}"}{iMyStatusProperty}和{iMyKey}是类实例的属性值所以问题是如何从属性中获取属性名(反射)而不用usingthepropertynameasastring(为了避免字段名拼写错误。)以上为C#学习教程:获取C#属性名或属性分享全文,网络收藏,不代表立场,如涉及侵权,请点击右边联系管理员删除,如需转载请注明出处:
