简体   繁体   中英

How to execute C# code at runtime in Xamarin Android?

I have a android application in Xamarin Studio. I want to execute a code placed in the text (string). For example this question help me in Visual Studio Windows application. But I cannot use this answer in Xamarin Android. This is my example in C# Windows application:

public class CodeLuncher
{
    public static void LunchCSCode(string site, string typeName, string methosName)
    {
        try
        {
            var provider = CSharpCodeProvider.CreateProvider("c#");
            var options = new CompilerParameters();
            string text = new System.Net.WebClient().DownloadString(site);

            foreach (var item in GetRefrences(text))
            {
                options.ReferencedAssemblies.Add(item);
            }
            string code = GetCode(text);
            var results = provider.CompileAssemblyFromSource(options, new[] { code });
            if (results.Errors.Count > 0)
            {
                foreach (var error in results.Errors)
                {
                    Console.WriteLine(error);
                }
            }
            else
            {
                var t = results.CompiledAssembly.GetType(typeName);
                t.GetMethod(methosName).Invoke(null, null);
            }
        }
        catch
        {

        }
    }


    static string[] GetRefrences(string text)
    {
        Regex regExp = new Regex("<Refrences>(.*?)</Refrences>", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
        string str = regExp.Match(text).Groups[1].Value;
        List<string> retText = new List<string>();
        foreach (var item in str.Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
        {
            retText.Add(item);
        }
        return retText.ToArray();
    }

    static string GetCode(string text)
    {
        Regex regExp = new Regex("<CSharpCode>(.*?)</CSharpCode>", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
        string str = regExp.Match(text).Groups[1].Value;
        return str.Trim();
    }
}

It's complicated http://developer.xamarin.com/guides/android/advanced_topics/limitations/

Since applications on Android require generating Java proxy types during the build process, it is not possible to generate all code at runtime.

From the Limited Dynamic Language Support and Limited Java Generation Support you can learn more about what specifically isn't supported. This means you might be able to work out certain code, but it won't work for any valid c# code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM