访问C#属性名称或属性 [英] Accessing C# property name or attributes

查看:132
本文介绍了访问C#属性名称或属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想自动生成一个类实例的SQL语句。该方法看起来应该像更新(对象[]属性,对象PrimaryKeyProperty)。该方法是一个实例(类的基本方法 - 通用所有子)的一部分。属性数组是类属性的数组,将在更新的语句中使用。属性名称等于表字段名称。

I would like to automatically generate SQL statements from a class instance. The method should look like Update(object[] Properties, object PrimaryKeyProperty). The method is part of an instance (class, base method - generic for any child). Array of properties is an array of class properties, that will be used in update statement. Property names are equal to table field names.

的问题是,我不能得到属性名称。

The problem is that I can't get property names.

是否有任何选项来获得类实例的内部属性名称?
样品:

Is there any option to get a property name inside class instance? sample:

public class MyClass {
public int iMyProperty { get; set; }
public string cMyProperty2 { get; set; }
{

main() {
 MyClass _main = new MyClass();

_main.iMyProperty.*PropertyName* // should return string "iMyProperty"

{

我知道的PropertyInfo,但我不知道烫获取属性从的GetProperties的ID()数组。

I am aware of PropertyInfo, but I don't know hot to get the ID of a property from GetProperties() array.

任何建议?

推荐答案

就写了这对lambda表达式为我们的最后一个星期二所在的用户组演示的实现。

Just wrote an implementation of this for a presentation on lambdas for our usergroup last Tuesday.


  • 您可以做

  • You can do

MembersOf<动物> .GetName(X => x.Status)

MembersOf<Animal>.GetName(x => x.Status)

VAR一个=新的动物()
a.MemberName(X = > x.Status)

var a = new Animal() a.MemberName(x => x.Status)

中的代码:

public static class MembersOf<T> {
    public static string GetName<R>(Expression<Func<T,R>> expr) {
        var node = expr.Body as MemberExpression;
        if (object.ReferenceEquals(null, node)) 
            throw new InvalidOperationException("Expression must be of member access");
        return node.Member.Name;
    }
}



查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆