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

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

這個方法會搜尋 expression 。具名稱 propertyOrFieldName 的實例屬性或欄位類型及其基底類型。 不支援靜態屬性或欄位。 公用屬性和欄位會優先于非公用屬性和欄位。 此外,屬性也會優先于欄位。 如果找到相符的屬性或欄位,這個方法會分別將 代表該屬性或欄位的 和 PropertyInfo FieldInfo 傳遞 expressionPropertyField

適用於