Имя свойства Accessing C# или атрибуты

Я использую основы -' :ls' +' :bn' / ':bp' +' :b <part-of-name>'

14
задан Alfred Myers 10 September 2009 в 22:56
поделиться

5 ответов

Только что написал реализацию этого для презентации лямбда-выражений для нашей группы пользователей в прошлый вторник.

  • Вы можете сделать

    MembersOf .GetName (x => x .Status)

  • Или

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

the code:

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;
    }
}
28
ответ дан 1 December 2019 в 06:21
поделиться

You can get the name (I assume that's what you meant by ID) of a property using PropertyInfo.Name. Just loop through the PropertyInfo[] returned from typeof(className).GetProperties()

foreach (PropertyInfo info in typeof(MyClass).GetProperties())
{
    string name = info.Name;
    // use name here
}
2
ответ дан 1 December 2019 в 06:21
поделиться

You can do something like this:

Type t = someInstance.getType();

foreach (MemberInfo mi in t.GetMembers())
{
    if (mi.MemberType == MemberTypes.Property)
    {
        Console.WriteLine(mi.Name);
    }
}

to get all the property names for instance's type.

6
ответ дан 1 December 2019 в 06:21
поделиться

Since you already have an explicit handle to the specific property you want, you know the name - can you just type it?

1
ответ дан 1 December 2019 в 06:21
поделиться

Скажем (из первого примера, обновление метода класса MyClass ):

public class MyClass {

public int iMyStatusProperty { get; set; }
public int iMyKey { get; set; }

public int UpdateStatusProperty(int iValue){
this.iMyStatusProperty = iValue;
return _Update( new[iMyStatusProperty ], iMyKey); // this should generate SQL: "UPDATE MyClass set iMyStatusProperty = {iMyStatusProperty} where iMyKey = {iMyKey}"
}

{iMyStatusProperty} и {iMyKey} являются значениями свойств экземпляра класса.

Итак, проблема в том, как получить имя свойства ( отражение ) из свойства без использования имен свойств в виде строк (чтобы избежать опечаток в имени поля).

1
ответ дан 1 December 2019 в 06:21
поделиться
Другие вопросы по тегам:

Похожие вопросы: