更改事件后在文本框上执行或编译运行时c#代码-“ PlatformNotSupportedException”

问题描述 投票:-1回答:1

我想在我的应用程序中向用户提供一个选项,以便能够使用Blazor自定义ASP.NET CORE中的按钮。

我的意思是,C#代码可以存储在数据库中,并且可以在运行时编译/执行。

如何在剃须刀中“提供”一个对象,以便在此“存储在数据库中的代码”中进行操作,然后在执行代码后在运行时进行这些更改?

请分享您的想法。

我已经尝试过一些方法,例如:

using Blazored.Toast.Services; 
using Microsoft.AspNetCore.Components; 
using Microsoft.CSharp;using Newtonsoft.Json; 
using System; 
using System.CodeDom.Compiler; 
using System.Collections.Generic; 
using System.Linq; 
using System.Reflection;
using System.Threading.Tasks;  

namespace Projeto.Web.Pages.Components {

public class McwEditModel : CustomComponentBase
{
    [Inject]
    public IToastService ToastService { get; set; }

    #region Parameters
    [Parameter]
    public string nome { get; set; }
    #endregion

    public void OnTextChanged(string newValue)
    {


        string source =
          @"public class SomeClass {
                public int OnTextChanged (string newValue) {
                    if (!string.IsNullOrEmpty(newValue))    {
                         ToastService.ShowWarning(newValue);
                }
                }
            } ";


       var compParms = new CompilerParameters
        {
            GenerateExecutable = false,
            GenerateInMemory = true
        };
        var csProvider = new CSharpCodeProvider();
        CompilerResults compilerResults =
            csProvider.CompileAssemblyFromSource(compParms, source);
        object typeInstance =
            compilerResults.CompiledAssembly.CreateInstance("SomeClass");
        MethodInfo mi = typeInstance.GetType().GetMethod("OnTextChanged");
        int methodOutput =
            (int)mi.Invoke(typeInstance, new object[] { newValue });

        InvokeAsync(StateHasChanged);
    }
}}

问题是无法正常工作,特别是我收到错误消息“ System.PlatformNotSupportedException:此平台不支持该操作。”,在线

" CompilerResults compilerResults =              csProvider.CompileAssemblyFromSource(compParms, source); "

我正在使用Blazor .NET Core。

有没有机会或方式实现我想要的?

runtime blazor codedom .net-core-3.1
1个回答
0
投票

我使用Microsoft.CodeAnalysis包解决了它。

我需要创建一个

public class Globals

    {
        [Inject]
        public IToastService ToastService { get; set; }

        public string newValue { get; set; }

        public dynamic objeto { get; set; }
    }

在我的方法中,我做了:

public void OnTextChanged(string newValue){

        Aql aql = new Aql { EaqcCodigo = "1", EaqcDescricao = "AQL" };

        var globals = new Globals { ToastService =  ToastService, newValue = newValue, objeto= aql };


        CSharpScript.RunAsync("ToastService.ShowWarning(newValue + \"- desc:\" + objeto.EaqcDescricao + \"- cod:\" + objeto.EaqcCodigo);", ScriptOptions.Default.WithReferences("Microsoft.CSharp"), globals).Wait();
    }

有了这个,现在我可以传递一个动态对象,并且还可以在数据库的字符串字段中编写任何代码,然后在我想要的任何地方检索它,以自定义很多内容,即:更改字段(在自定义的通用和动态组件中)

© www.soinside.com 2019 - 2024. All rights reserved.