Expression.PropertyOrField(Expression, String) Метод

Определение

Создает объект MemberExpression, представляющий доступ к свойству или полю.

public:
 static System::Linq::Expressions::MemberExpression ^ PropertyOrField(System::Linq::Expressions::Expression ^ expression, System::String ^ propertyOrFieldName);
public static System.Linq.Expressions.MemberExpression PropertyOrField (System.Linq.Expressions.Expression expression, string propertyOrFieldName);
static member PropertyOrField : System.Linq.Expressions.Expression * string -> System.Linq.Expressions.MemberExpression
Public Shared Function PropertyOrField (expression As Expression, propertyOrFieldName As String) As MemberExpression

Параметры

expression
Expression

Expression, в свойстве Type которого содержится свойство или поле с именем, заданным параметром propertyOrFieldName.

propertyOrFieldName
String

Имя свойства или поля для доступа.

Возвращаемое значение

Выражение MemberExpression, имеющее свойство NodeType, равное MemberAccess, свойство Expression, для которого задано значение expression, и свойство Member, для которого задано значение PropertyInfo или FieldInfo, представляющее свойство или поле, обозначенное с помощью параметра propertyOrFieldName.

Исключения

Параметр expression или propertyOrFieldName имеет значение null.

Не определено свойство или поле с именем propertyOrFieldName для типа expression.Type или его базовых типов.

Примеры

В следующем примере показано, как создать выражение, представляющее доступ к свойству или полю.

// Add the following directive to your file:
// using System.Linq.Expressions;

class TestClass
{
    public int sample { get; set; }
}

static void TestPropertyOrField()
{
    TestClass obj = new TestClass();
    obj.sample = 40;

    // This expression represents accessing a property or field.
    // For static properties or fields, the first parameter must be null.
    Expression memberExpr = Expression.PropertyOrField(
        Expression.Constant(obj),
        "sample"
    );

    // The following statement first creates an expression tree,
    // then compiles it, and then runs it.
    Console.WriteLine(Expression.Lambda<Func<int>>(memberExpr).Compile()());
}

// This code example produces the following output:
//
// 40
' Add the following directive to your file:
' Imports System.Linq.Expressions  

Class TestClass
    Public Property Sample As Integer
End Class

Sub TestPropertyOrField()

    Dim obj As New TestClass()
    obj.Sample = 40

    ' This expression represents accessing a property or field.
    ' For static properties or fields, the first parameter must be Nothing.
    Dim memberExpr As Expression = Expression.PropertyOrField(
          Expression.Constant(obj),
          "Sample"
      )

    ' The following statement first creates an expression tree,
    ' then compiles it, and then runs it.
    Console.WriteLine(Expression.Lambda(Of Func(Of Integer))(memberExpr).Compile()())
End Sub

' This code example produces the following output:
'
' 40

Комментарии

Свойство Type результирующего MemberExpression объекта равно PropertyType свойствам PropertyInfo или FieldType , FieldInfoсоответственно, которые представляют свойство или поле, обозначаемое параметром propertyOrFieldName.

Этот метод выполняет поиск expression. Тип и его базовые типы для свойства или поля экземпляра с именем propertyOrFieldName. Статические свойства или поля не поддерживаются. Общедоступным свойствам и полям отдается предпочтение по сравнению с не открытыми свойствами и полями. Кроме того, свойствам отдается предпочтение перед полями. При обнаружении соответствующего свойства или поля этот метод передает expression и PropertyInfo или FieldInfo , представляющий это свойство или поле, в Property или Fieldсоответственно.

Применяется к