【问题标题】:CSharpScript.EvaluateAsync not recognising enumCSharpScript.EvaluateAsync 无法识别枚举
【发布时间】:2020-12-28 02:38:50
【问题描述】:

我正在使用CSharpScript.EvaluateAsync 从字符串生成谓词。使用字符串和 int 变量可以正常工作,但是如果我尝试在字符串中传入枚举变量进行转换,则会引发错误:

消息“(1,26):错误CS0103:当前上下文中不存在名称'Status'”字符串

这是独立的复制品:

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
    }
    
}

如何让它与枚举一起使用?

【问题讨论】:

    标签: c# roslyn


    【解决方案1】:
    var options = ScriptOptions.Default.AddReferences(typeof(T).Assembly).AddImports(nameof(PredicateParser));
    

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

    【讨论】:

      【解决方案2】:

      在这种情况下,如果您使用命名空间完全限定它,则不会出错。

      "album => album.Status == PredicateParser.Status.Online"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-24
        • 2017-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-08
        相关资源
        最近更新 更多