如何使用字符串参数来区分命名空间或类型?

2024-05-11

我需要在 .NET 2.0 C# 脚本中获取一些 JSON 输出。目标是使用一种方法来输出我需要的所有 JSON 提要。所有模型都具有相同的 id 和 name 属性,因此我有大约 15 个命名空间,它们在这里具有相同的部分。简而言之:因为我使用 castle,所以我可以调用该函数,如下所示:

/public/get_place_tags.castle
/public/get_place_types.castle
/public/get_place_whichEver.castle

城堡中哪个正在调用每个方法,即:get_place_tags(){}但我不想在可以调用一种方法来获取每种类型的输出的地方工作,如下所示:

/public/get_json.castle?wantedtype=place_types

有谁知道如何解决这一问题?

namespace campusMap.Controllers
{
    [Layout("home")]
    public class PublicController : BaseController
    {
        /*  works and returns */
        public void get_pace_type()
        {
            CancelView();
            CancelLayout();

            place_types[] types = ActiveRecordBase<place_types>.FindAll();
            List<JsonAutoComplete> type_list = new List<JsonAutoComplete>();

            foreach (place_types place_type in types)
            {
                JsonAutoComplete obj = new JsonAutoComplete();

                obj.id = place_type.place_type_id;
                obj.label = place_type.name;
                obj.value = place_type.name;

                type_list.Add(obj);
            }

            string json = JsonConvert.SerializeObject(type_list);
            RenderText(json);
        }

        /*  can;t ever find the namespace */
        public void get_json(string wantedtype)
        {
            CancelView();
            CancelLayout();
            Type t = Type.GetType(wantedtype); 

            t[] all_tag = ActiveRecordBase<t>.FindAll();
            List<JsonAutoComplete> tag_list = new List<JsonAutoComplete>();

            foreach (t tag in all_tag)
            {
                JsonAutoComplete obj = new JsonAutoComplete();

                obj.id = tag.id;
                obj.label = tag.name;
                obj.value = tag.name;

                tag_list.Add(obj);
            }

            string json = JsonConvert.SerializeObject(tag_list);
            RenderText(json);
        }
    }
}

[编辑]--(最新想法)运行时类型创建..我认为这是让它发挥作用的最干净的想法...-----

所以目标实际上是在运行时使用一种类型……对……所以我认为这会起作用。http://www.java2s.com/Code/CSharp/Development-Class/Illustratesruntimetypecreation.htm http://www.java2s.com/Code/CSharp/Development-Class/Illustratesruntimetypecreation.htm到目前为止,这是基于此的方法。我仍然遇到问题t克服错误 “无法找到类型或命名空间名称“t”(您是否缺少 using 指令或程序集引用?)”.. 不确定我在哪里出错了。似乎无法让它发挥作用,哈哈..

public void get_json(String TYPE)
{
    CancelView();
    CancelLayout();
    if (String.IsNullOrEmpty(TYPE))
    {
        TYPE = "place_types";
    }
    // get the current appdomain
    AppDomain ad = AppDomain.CurrentDomain;

    // create a new dynamic assembly
    AssemblyName an = new AssemblyName();
    an.Name = "DynamicRandomAssembly";
    AssemblyBuilder ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);

    // create a new module to hold code in the assembly
    ModuleBuilder mb = ab.DefineDynamicModule("RandomModule");

    // create a type in the module
    TypeBuilder tb = mb.DefineType(TYPE, TypeAttributes.Public);

    // finish creating the type and make it available
    Type t = tb.CreateType();
    t[] all_tag = ActiveRecordBase<t>.FindAll();

    List<JsonAutoComplete> tag_list = new List<JsonAutoComplete>();
    foreach (t tag in all_tag)
    {
        JsonAutoComplete obj = new JsonAutoComplete();
        obj.id = tag.id;
        obj.label = tag.name;
        obj.value = tag.name;
        tag_list.Add(obj);
    }
    RenderText(JsonConvert.SerializeObject(tag_list)); 
}

[编辑]--(较旧的想法)Eval 代码-----

因此,实现这一目标的尝试是使用反射和其他东西来基于此进行某种评估http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=11939 http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=11939

namespace EvalCSCode
{
    /// <summary>
    /// Interface that can be run over the remote AppDomain boundary.
    /// </summary>
    public interface IRemoteInterface
    {
        object Invoke(string lcMethod, object[] Parameters);
    }


    /// <summary>
    /// Factory class to create objects exposing IRemoteInterface
    /// </summary>
    public class RemoteLoaderFactory : MarshalByRefObject
    {
        private const BindingFlags bfi = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;

        public RemoteLoaderFactory() { }

        /// <summary> Factory method to create an instance of the type whose name is specified,
        /// using the named assembly file and the constructor that best matches the specified parameters. </summary>
        /// <param name="assemblyFile"> The name of a file that contains an assembly where the type named typeName is sought. </param>
        /// <param name="typeName"> The name of the preferred type. </param>
        /// <param name="constructArgs"> An array of arguments that match in number, order, and type the parameters of the constructor to invoke, or null for default constructor. </param>
        /// <returns> The return value is the created object represented as ILiveInterface. </returns>
        public IRemoteInterface Create(string assemblyFile, string typeName, object[] constructArgs)
        {
            return (IRemoteInterface)Activator.CreateInstanceFrom(
                assemblyFile, typeName, false, bfi, null, constructArgs,
                null, null, null).Unwrap();
        }
    }
}


#endregion
namespace campusMap.Controllers
{

    public class JsonAutoComplete
    {
        private int Id;
        [JsonProperty]
        public int id
        {
            get { return Id; }
            set { Id = value; }
        }
        private string Label;
        [JsonProperty]
        public string label
        {
            get { return Label; }
            set { Label = value; }
        }
        private string Value;
        [JsonProperty]
        public string value
        {
            get { return Value; }
            set { Value = value; }
        }
    }


    [Layout("home")]
    public class publicController : BaseController
    {
        #region JSON OUTPUT
        /*  works and returns */
        public void get_pace_type()
        {
            CancelView();
            CancelLayout();
            place_types[] types = ActiveRecordBase<place_types>.FindAll();

            List<JsonAutoComplete> type_list = new List<JsonAutoComplete>();
            foreach (place_types place_type in types)
            {
                JsonAutoComplete obj = new JsonAutoComplete();
                obj.id = place_type.id;
                obj.label = place_type.name;
                obj.value = place_type.name;
                type_list.Add(obj);
            }
            string json = JsonConvert.SerializeObject(type_list);
            RenderText(json);
        }
        /*  how I think it'll work to have a dynmaic type */
        public void get_json(string type)
        {
            CancelView();
            CancelLayout();
            /*t[] all_tag = ActiveRecordBase<t>.FindAll();

            List<JsonAutoComplete> tag_list = new List<JsonAutoComplete>();
            foreach (t tag in all_tag)
            {
                JsonAutoComplete obj = new JsonAutoComplete();
                obj.id = tag.id;
                obj.label = tag.name;
                obj.value = tag.name;
                tag_list.Add(obj);
            }*/
            StringBuilder jsonobj = new StringBuilder("");
            jsonobj.Append(""+type+"[] all_tag = ActiveRecordBase<"+type+">.FindAll();\n");
            jsonobj.Append("List<JsonAutoComplete> tag_list = new List<JsonAutoComplete>();{\n");
            jsonobj.Append("foreach ("+type+" tag in all_tag){\n");
            jsonobj.Append("JsonAutoComplete obj = new JsonAutoComplete();\n");
            jsonobj.Append("obj.id = tag.id;\n");
            jsonobj.Append("obj.label = tag.name;\n");
            jsonobj.Append("obj.value = tag.name;\n");
            jsonobj.Append("tag_list.Add(obj);\n");
            jsonobj.Append("}\n");

            CSharpCodeProvider c = new CSharpCodeProvider();
            ICodeCompiler icc = c.CreateCompiler();
            CompilerParameters cp = new CompilerParameters();

            cp.ReferencedAssemblies.Add("system.dll");
            cp.ReferencedAssemblies.Add("Newtonsoft.Json.Net20.dll");
            cp.ReferencedAssemblies.Add("Castle.ActiveRecord.dll");

            cp.CompilerOptions = "/t:library";
            cp.GenerateInMemory = true;

            StringBuilder sb = new StringBuilder("");
            sb.Append("namespace CSCodeEvaler{ \n");
            sb.Append("public class CSCodeEvaler{ \n");
            sb.Append("public object EvalCode(){\n");
            sb.Append("return " + jsonobj + "; \n");
            sb.Append("} \n");
            sb.Append("} \n");
            sb.Append("}\n");

            CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());
            System.Reflection.Assembly a = cr.CompiledAssembly;
            object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");

            Type t = o.GetType();
            MethodInfo mi = t.GetMethod("EvalCode");

            object s = mi.Invoke(o, null); 

            string json = JsonConvert.SerializeObject(s);
            RenderText(json);
        }/**/
        #endregion
   }

我知道有人建议不需要使用..我知道我不了解它们,也许这是水平显示..但这里它们是我认为在上面起作用的。

using System;
using System.Collections;
using System.Collections.Generic;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Queries;
using Castle.MonoRail.Framework;
using Castle.MonoRail.ActiveRecordSupport;
using campusMap.Models;
using MonoRailHelper;
using System.IO;
using System.Net;
using System.Web;
using NHibernate.Expression;
using System.Xml;
using System.Xml.XPath;
using System.Text.RegularExpressions;
using System.Text;
using System.Net.Sockets;
using System.Web.Mail;
using campusMap.Services;


using Newtonsoft.Json;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;

using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.IO;
using System.Threading;
using System.Reflection;

好吧,这只是一个建议,我对城堡一无所知,但在我看来,你想要一条自定义路线。

这是未经测试的,当然你必须调整它,但看看你的 Global.asax RegisterRoutes 方法并将其添加到默认路由之上

        routes.MapRoute(
            "TypeRoute", // Route name
            "Public/{wantedtype}", // URL with parameters
            new { controller = "Public", action = "get_json", wantedtype = UrlParameter.Optional } // Parameter defaults
        );

像这样的东西可能会得到你想要的东西。

您可能需要摆弄动作,使其与您的城堡框架相匹配

EDIT

我还有一些时间来看看这个。使用我上面描述的路线和控制器上的以下方法我得到了很好的结果

    public void get_json(string wantedtype)
    {
        Type t = Type.GetType(wantedtype);
        // t.Name = "Int32" when "System.Int32 is used as the wanted type
    }

http://.../Public/System.Int32 http://.../Public/System.Int32作品, 这个网址不起作用http://.../Public/Int32 http://.../Public/Int32

现在,如果您想使用简短版本,您可以使用 MEF 或 AutoFAC 或 Castle 等工具在容器中查找所需的类型。

所以我的答案是使用一个好的路线来获取所需类型的密钥,然后构建一个工厂来管理类型映射并生成您想要的实例。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用字符串参数来区分命名空间或类型? 的相关文章

  • C# 中的 Stack<> 实现

    我最近一直在实现递归目录搜索实现 并且使用堆栈来跟踪路径元素 当我使用 string Join 连接路径元素时 我发现它们被颠倒了 当我调试该方法时 我查看了堆栈 发现堆栈内部数组中的元素本身是相反的 即最近 Push 的元素位于内部数组的
  • 在 C 语言中,为什么数组的地址等于它的值?

    在下面的代码中 指针值和指针地址与预期不同 但数组值和地址则不然 怎么会这样 Output my array 0022FF00 my array 0022FF00 pointer to array 0022FF00 pointer to a
  • strlen() 编译时优化

    前几天我发现你可以找到编译时strlen使用这样的东西 template
  • 在 C++ 代码中转换字符串

    我正在学习 C 并开发一个项目来练习 但现在我想在代码中转换一个变量 字符串 就像这样 用户有一个包含 C 代码的文件 但我希望我的程序读取该文件并插入将其写入代码中 如下所示 include
  • 2个对象,完全相同(除了命名空间)c#

    我正在使用第三方的一组网络服务 但遇到了一个小障碍 在我手动创建将每个属性从源复制到目标的方法之前 我想我应该在这里寻求更好的解决方案 我有 2 个对象 一个是 Customer CustomerParty 类型 另一个是 Appointm
  • Android NDK 代码中的 SIGILL

    我在市场上有一个 NDK 应用程序 并获得了有关以下内容的本机崩溃报告 SIGILL信号 我使用 Google Breakpad 生成本机崩溃报告 以下是详细信息 我的应用程序是为armeabi v7a with霓虹灯支持 它在 NVIDI
  • if constexpr 中的 not-constexpr 变量 – clang 与 GCC

    struct A constexpr operator bool const return true int main auto f auto v if constexpr v A a f a clang 6 接受该代码 GCC 8 拒绝它
  • C# 根据当前日期传递日期时间值

    我正在尝试根据 sql server 中的两个日期获取记录 Select from table where CreatedDate between StartDate and EndDate我通过了5 12 2010 and 5 12 20
  • OpenGL:如何检查用户是否支持glGenBuffers()?

    我检查了文档 它说 OpenGL 版本必须至少为 1 5 才能制作glGenBuffers 工作 用户使用的是1 5版本但是函数调用会导致崩溃 这是文档中的错误 还是用户的驱动程序问题 我正在用这个glGenBuffers 对于VBO 我如
  • wordexp 失败时我们需要调用 wordfree 吗?

    wordexp 失败时我们需要调用 wordfree 吗 在某些情况下 调用 wordfree 似乎会出现段错误 例如 当 wordfree 返回字符串为 foo bar 的错误代码时 这在手册页中并不清楚 我已经看到在某些错误情况下使用了
  • 如何防止 Blazor NavLink 组件的默认导航

    从 Blazor 3 1 Preview 2 开始 应该可以防止默认导航行为 https devblogs microsoft com aspnet asp net core updates in net core 3 1 preview
  • Unity c# 四元数:将 y 轴与 z 轴交换

    我需要旋转一个对象以相对于现实世界进行精确旋转 因此调用Input gyro attitude返回表示设备位置的四元数 另一方面 这迫使我根据这个四元数作为默认旋转来计算每个旋转 将某些对象设置为朝上的简单方法如下 Vector3 up I
  • SQLAPI++ 的免费替代品? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 是否有任何免费 也许是开源 的替代品SQLAPI http www sqlapi com 这个库看起来
  • ASP.NET Core 中间件与过滤器

    在阅读了 ASP NET Core 中间件之后 我对何时应该使用过滤器以及何时应该使用中间件感到困惑 因为它们似乎实现了相同的目标 什么时候应该使用中间件而不是过滤器 9频道有一个关于此的视频 ASP NET 怪物 91 中间件与过滤器 h
  • 读取依赖步行者输出

    I am having some problems using one of the Dlls in my application and I ran dependency walker on it i am not sure how to
  • 构建 C# MVC 5 站点时项目之间的处理器架构不匹配

    我收到的错误如下 2017 年 4 月 20 日构建 13 23 38 C Windows Microsoft NET Framework v4 0 30319 Microsoft Common targets 1605 5 警告 MSB3
  • 如何编写一个接受 int 或 float 的 C 函数?

    我想用 C 语言创建一个扩展 Python 的函数 该函数可以接受 float 或 int 类型的输入 所以基本上 我想要f 5 and f 5 5 成为可接受的输入 我认为我不能使用if PyArg ParseTuple args i v
  • 如何从 Windows Phone 7 模拟器获取数据

    我有一个 WP7 的单元测试框架 它在手机上运行 结果相当难以阅读 因此我将它们写入 XDocument 我的问题是 如何才能将这个 XML 文件从手机上移到我的桌面上 以便我可以实际分析结果 到目前为止 我所做的是将 Debugger B
  • 声明一个负长度的数组

    当创建负长度数组时 C 中会发生什么 例如 int n 35 int testArray n for int i 0 i lt 10 i testArray i i 1 这段代码将编译 并且启用 Wall 时不会出现警告 并且似乎您可以分配
  • 如果找不到指定的图像文件,显示默认图像的最佳方式?

    我有一个普通的电子商务应用程序 我将 ITEM IMAGE NAME 存储在数据库中 有时经理会拼错图像名称 为了避免 丢失图像 IE 中的红色 X 每次显示产品列表时 我都会检查服务器中是否有与该产品相关的图像 如果该文件不存在 我会将其

随机推荐