csharp 获取属性名称为字符串

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 获取属性名称为字符串相关的知识,希望对你有一定的参考价值。

// This lets you get the name of a field as a string.
// When calling BOReader or other things that require string names, the compiler can't 
// validate the field names.
// Now it can! No more shit blowing up because you fat fingered a field name.
// Also, schema changes will make the code fail to compile so you upgrades are simpler!

// Saddly it does require linq.

// <summary>
// Get the name of a static or instance property from a property access lambda.
// </summary>
// <typeparam name="T">Type of the property</typeparam>
// <param name="propertyLambda">lambda expression of the form: '() => Class.Property' or '() => object.Property'</param>
// <returns>The name of the property</returns>
public string GetPropertyName<T>(Expression<Func<T>> propertyLambda){
    var me = propertyLambda.Body as MemberExpression;
    if (me == null)
        throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
    return me.Member.Name;
 }
 
// Usage
var Part = new PartDataSet();
var PartNum = GetPropertyName(() => Part.Part[0].PartNum);
var PartDescription = GetPropertyName(() => Part.Part[0].PartDescription);

var bor = WCFServiceSupport.CreateImpl<BOReaderImpl>((Session)oTrans.Session, ImplBase<BOReaderSvcContract>.UriPath);
var partData = bor.GetRows("Erp:BO:Part", 
    string.Format("{0}='SuperPart'", PartNum), 
    string.Format("{0},{1}", PartNum, PartDescription));
 
 

以上是关于csharp 获取属性名称为字符串的主要内容,如果未能解决你的问题,请参考以下文章

c#发送后如何获取邮件名称(uid)[关闭]

以字符串形式获取对象属性名称

获取基于属性名称的 Vue 数据模型属性的值?

Citrix Xendesktop更改发布桌面的显示名称

通过字符串名称设置/获取类属性[重复]

获取“名称”属性时出错:属性不是字符串值 Hybrid Cordova App