📜  C#7.1 默认表达式

📅  最后修改于: 2020-11-01 03:12:25             🧑  作者: Mango

C#默认表达式

C#默认表达式是一个类(DefaultExpression),用于表示空表达式的默认值。它是System.Linq.Expressions.Expression命名空间的子类。

为了获取表达式的默认值,Expression类提供了一个静态方法Default(Type),该方法返回DefaultExpression类的实例。

C#DefaultExpression类语法

public sealed class DefaultExpression : Expression

它提供以下属性和方法。

C#DefaultExpression属性

Name Description
CanReduce This property is inherited from Expressionn. It Indicates that the node can be reduced to a simpler node.
NodeType It is used to return the node type of this expression.
Type Gets the static type of the expression that this Expression represents.

C#DefaultExpression方法

Name Description
Accept(ExpressionVisitor) It is used to dispatch the specific visit method for this node type.
Equals(Object) It determines whether the specified object is equal to the current object or not.
GetHashCode() This method serves as the default hash function.
GetType() It is used to get the type of the current instance.
Reduce() It is used to reduce this node to a simpler expression.
ReduceAndCheck() It is used to reduce this node to a simpler expression by explicit checking.
ReduceExtensions() It reduces the expression to a known node type.
ToString() It is used to return a string representation of the Expression.
VisitChildren(ExpressionVisitor) It reduces the node and then calls the visitor delegate on the reduced expression.

Expression.Default()方法具有以下签名。

public static DefaultExpression Default(Type type)

它采用System.Type类型的参数,并返回DefaultExpression类的实例。

C#默认表达式示例

using System;
using System.Linq.Expressions;
namespace CSharpFeatures
{
    class AsynchronousMethod
    {
        public static void Main(string[] args = default)
        {
            Expression defaultExpression = Expression.Default(typeof(int));
            show(defaultExpression);
        }
        static void show(Expression defaultExpression)
        {
            // Default expression properties and methods
            Console.WriteLine("Instace:       "  + defaultExpression);
            Console.WriteLine("Type:          "  + defaultExpression.Type);
            Console.WriteLine("Can reduce:    "  + defaultExpression.CanReduce);
            Console.WriteLine("Instance type: "  + defaultExpression.GetType());
            Console.WriteLine("Node type:     "  + defaultExpression.NodeType);
        }
    }
}

输出:

Instace:       default(Int32)
Type:          System.Int32
Can reduce:    False
Instance type: System.Linq.Expressions.DefaultExpression
Node type:     Default