Roslyn, passing values through hostObject

你离开我真会死。 提交于 2019-12-06 04:13:01

问题


I am trying to send one class through hostObject but apparently it doesn't want to work:

using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;
using Roslyn.Scripting;
using Roslyn.Scripting.CSharp;


public class ShippingService
{
    public class ShippingDetails//class that I want to send
    {
        public decimal total { get; set; }
        public int quantity { get; set; }
        public string destination { get; set; }
    }
    public static string ShipingCost(decimal total, int quantity, string destination)
    {
        var details = new ShippingDetails
        {
            total = total,
            quantity = quantity,
            destination = destination
        };

        try
            {
                ScriptEngine roslynEngine = new ScriptEngine();
                Roslyn.Scripting.Session session = roslynEngine.CreateSession(details);
                session.AddReference(details.GetType().Assembly);
                session.AddReference("System.Web");
                session.ImportNamespace("System");
                session.ImportNamespace("System.Web");
                var result = session.Execute("details.destination");
                return result;
            }
        catch (Exception e)
            {
            return e.Message;
            }
        return "";
    }   

}

When I am calling the function destination is for example "France", and I should get this value in result but i am getting mistake:

Roslyn.Compilers.CompilationErrorException: (1,1): error CS0103: The name 'details' does not exist in the current context


回答1:


The error message is exactly right. When you have a host object, you can't access it by the name of the local variable that holds it in your method (how would that even work? how would ScriptEngine learn that name?).

Instead, you can access the host object directly, almost as if you were writing a member method of that type (but not quite, you can't use this or access non-public members).

This means that you should write just:

session.Execute("destination")

BTW, according to .Net naming guidelines, names of public properties should start with upper case letter (e.g. Destination).



来源:https://stackoverflow.com/questions/19272764/roslyn-passing-values-through-hostobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!