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 屬性等於 MemberAccessExpression 屬性設定為 expression,且 Member 屬性設定為 PropertyInfoFieldInfo,代表 propertyOrFieldName 所表示的屬性或欄位。

例外狀況

expressionpropertyOrFieldNamenull

propertyOrFieldName.Type 或其基底類型中沒有定義名為 expression 的屬性或欄位。

範例

下列範例示範如何建立代表存取屬性或欄位的表達式。

// 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 或 的 或 FieldInfoFieldType 屬性PropertyInfo,分別代表 所propertyOrFieldName表示的屬性或欄位。

這個方法會搜尋 expression。類型及其基底類型,用於名稱為的 propertyOrFieldName實例屬性或欄位。 不支持靜態屬性或欄位。 公用屬性和欄位的喜好設定高於非公用屬性和欄位。 此外,屬性會優先於欄位。 如果找到相符的屬性或欄位,這個方法會分別將 代表該屬性或欄位的 與 PropertyInfoFieldInfo 傳遞expressionPropertyField

適用於