代码之家  ›  专栏  ›  技术社区  ›  Zachary Scott

如何在运行时定义C对象?

  •  5
  • Zachary Scott  · 技术社区  · 15 年前

    我们将XML代码存储在单个关系数据库字段中,以解决实体/属性/值数据库问题,但我不希望这会破坏我的域建模、DTO和存储库阳光。我无法绕过EAV/CR内容,但我可以选择如何存储它。问题是我如何使用它?

    如何在运行时将XML元数据转换为C中的类/对象?

    例如:

    XML将描述我们有一个食物配方,它具有各种属性,但通常是相似的,以及一个或多个关于制作食物的属性。食物本身可以是任何东西,也可以有任何疯狂的准备。搜索所有属性,并可链接到现有营养信息。

    // <-- [Model validation annotation goes here for MVC2]
    public class Pizza {
         public string kind  {get; set;}
         public string shape {get; set;}
         public string city  {get; set;}
         ...
    }
    

    在actionMethod中:

    makePizzaActionMethod (Pizza myPizza) {
        if (myPizza.isValid() ) {  // this is probably ModelState.isValid()...
            myRecipeRepository.Save( myPizza);
            return View("Saved");
        }
        else
            return View();
    }
    
    3 回复  |  直到 15 年前
        1
  •  9
  •   Foole    15 年前

    ExpandoObject 你在找什么?

    表示其成员可以 在处动态添加和删除 运行时间。

        2
  •  3
  •   Grant Back    15 年前

    退房 System.Reflection.Emit 命名空间。

    从appdomain.currentdomain中的assemblybuilder类开始

    AssemblyBuilder dynAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly("dynamic.dll",
                                                                                AssemblyBuilderAccess.RunAndSave);
    

    从那里你必须建立一个modulebuilder,从中你可以建立一个typebuilder。

    退房 AssmblyBuilder 示例参考。

    您可以保存生成的程序集,或者只在内存中使用它。不过,请注意,使用这些动态类型会使您陷入沉思。

    编辑:

    下面是如何迭代属性的示例:

    AssemblyName aName = new AssemblyName("dynamic");
    AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.RunAndSave);
    ModuleBuilder mb = ab.DefineDynamicModule("dynamic.dll");
    TypeBuilder tb = mb.DefineType("Pizza");
    //Define your type here based on the info in your xml
    Type theType = tb.CreateType();
    
    //instanciate your object
    ConstructorInfo ctor = theType.GetConstructor(Type.EmptyTypes);
    object inst = ctor.Invoke(new object[]{});
    
    PropertyInfo[] pList = theType.GetProperties(BindingFlags.DeclaredOnly);
    //iterate through all the properties of the instance 'inst' of your new Type
    foreach(PropertyInfo pi in pList)
        Console.WriteLine(pi.GetValue(inst, null));
    
        3
  •  1
  •   cdiggins    15 年前

    编辑:这不能解决原始海报的问题。

    我想这可能是用 XAML . 我将生成一个XAML文件,然后 load it dynamically using XamlReader.Load() 在运行时用我想要的属性创建一个对象。

    有一篇关于 XAML as an object serialization framework here . 有关更多信息 XAML namespaces see here .