CSharpScript.EvaluateAsync 无法识别枚举

CSharpScript.EvaluateAsync not recognising enum

我正在使用 CSharpScript.EvaluateAsync 从字符串生成谓词。使用字符串和 int 变量它工作正常但是如果我尝试在字符串中传递一个枚举变量来转换它会抛出错误:

Message "(1,26): error CS0103: The name 'Status' does not exist in the current context" string

这是独立的复制品:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;

namespace PredicateParser
{
    class Program
    {
        static void Main(string[] args)
        {
            var albums = new List<Album>
            {
                new Album { Quantity = 10, Artist = "Betontod", Title = "Revolution", Status = Status.Offline},
                new Album { Quantity = 50, Artist = "The Dangerous Summer", Title = "The Dangerous Summer", Status = Status.Offline },
                new Album { Quantity = 200, Artist = "Depeche Mode", Title = "Spirit", Status = Status.Online },
            };


            var albumFilter1 = "album => album.Quantity > 20 && album.Quantity < 200"; //works fine
            var albumFilter2 = "album => album.Status == Status.Online"; //Throws exception

            var predicate1 = CreatePredicate<Album>(albumFilter1);
            var predicate2 = CreatePredicate<Album>(albumFilter2);

            var filteredAlbums1 = albums.Where(predicate1).ToList();
            var filteredAlbums2 = albums.Where(predicate2).ToList();

        }

        public static Func<T, bool> CreatePredicate<T>(string command)
        {
            var options = ScriptOptions.Default.AddReferences(typeof(T).Assembly);
            Func<T, bool> predicate = CSharpScript.EvaluateAsync<Func<T, bool>>(command, options).Result;

            return predicate;
        }

    }



    public class Album
    {
        public int Quantity { get; set; }
        public string Title { get; set; }
        public string Artist { get; set; }
        public Status Status { get; set; }
    }

    public enum Status
    {
        Online,
        Offline
    }
    
}

如何让它与枚举一起工作?

在这种情况下,如果您使用命名空间对其进行完全限定,则不会出现错误。

"album => album.Status == PredicateParser.Status.Online"
var options = ScriptOptions.Default.AddReferences(typeof(T).Assembly).AddImports(nameof(PredicateParser));

您忘记添加“使用命名空间”:)