【问题标题】:How to add properties to a class at runtime in c# - From JSON file如何在 C# 中在运行时向类添加属性-来自 JSON 文件
【发布时间】:2020-10-28 08:54:27
【问题描述】:

我想创建一个可以在运行时动态分配属性的类。

我正在做的事情的简要总结:我正在创建一个程序,它将为不同的软件动态解析 XML 文件,并使用 MVC 在组织良好的表格中显示信息。每个软件应用程序都在我的 JSON 文件中定义,并具有某些属性。

JSON 文件示例:

    "AMZsoftware": {
     "APP1": {
     "ResponseTime": "2412",
     "Location": [ "tmd_7609", "tmd_61573" ],
     "Properties": ["Speed", "Capacity", "Security"]
      },
      "APP2": {
      "ResponseTime": "1712",
      "Location": [ "LT_13", "LT_00" ],
      "Properties": ["Speed", "Resilience", "Security"]   
      },
     "APP3": {
      "ResponseTime": "0117",
      "Location": [ "AP_99", "AP_47" ],
      "Properties": ["Database", "WorkFlow", "LZSettings"]   
      },
     };

这只是我的 JSON 文件的一小部分,但主要是如果您查看属性部分,则有一个属性列表。这些是需要在运行时分配的属性。我有不同的类,这些类将为我处理检索和存储数据。

如您所见,有些属性是重复的,但有些是不同的,我需要能够解释这些差异。我将 JSON 文件中的属性存储在字符串列表中。

我已经阅读了有关使用字典的文章,但是有没有一种方法可以创建具有动态属性的全新类?

当用户选择查看有关 APP1 的数据时,我想创建一个列出属性的类,然后我的程序将正常处理解析和事情。

一旦信息存储在这个动态类中,我会将它传递给视图并打印数据。提前感谢您的任何建议。

【问题讨论】:

  • 属性是字典,给你的类添加字典
  • @TheGeneral 哦,好吧,我明白了,让我试试。刚接触 c# 和 MVC,所以对所有可能的选项有点困惑。

标签: c# class dynamic properties


【解决方案1】:

从这里:“我有不同的类,这些类将为我处理检索和存储数据。”

如果我没看错的话,听起来您已经有了对属性进行操作的类。您可以创建一个所有这些类都基于的接口,然后使用类工厂通过将属性名称传递给工厂来返回对给定“属性”进行操作的类。

首先,在网络上搜索“C# 类工厂”,将会有大量关于类工厂模式如何工作的信息。

本质上,类工厂有一个接口、一个或多个实现该接口的类,以及一个返回实现该接口的类的实例的工厂。然后应用程序可以使用所有这些部分来执行某些任务。

这是我拼凑起来的一个小例子。

IMathOperation.cs

// The interface that all factory classes must implement:
interface IMathOperation
{
    string getName();
    string performOperation(int a, int b);
}

实现接口的类:

添加.cs

public class Add : IMathOperation
{
    public string getName()
    {
        return "Addition";
    }

    public string performOperation(int a, int b)
    {
        return string.Format("{0} + {1} = {2}", a, b, a+b);
    }

}

减去.cs

public class Subtract : IMathOperation
{
    public string getName()
    {
        return "Subtraction";
    }

    public string performOperation(int a, int b)
    {
        return string.Format("{0} - {1} = {2}", a, b, a-b);
    }

}

乘法.cs

public class Multiply : IMathOperation
{
    public string getName()
    {
        return "Multiplication";
    }

    public string performOperation(int a, int b)
    {
        return string.Format("{0} * {1} = {2}", a, b, a*b);
    }

}

Divide.cs

public class Divide : IMathOperation
{
    public string getName()
    {
        return "Division";
    }

    public string performOperation(int a, int b)
    {
        return string.Format("{0} / {1} = {2}", a, b, b != 0? ((float)((float)a / (float)b)).ToString() : "Divide by zero error");
    }

}

MathFactory.cs

class MathFactory
{

    public static IMathOperation getFactory(string mathOp)
    {
        switch (mathOp.ToUpper())
        {
            case "ADD":
            return new Add();

            case "SUB":
            return new Subtract();

            case "MUL":
            return new Multiply();

            case "DIV":
            return new Divide();
        }

        return null;
    }
}

程序.cs

using System;

namespace ClassFactory_C_Sharp {
    class Program
    {
        static void Main(string[] args)
        {
            IMathOperation op;

            Console.WriteLine("Hello Math Factory!\n");

            // try all the class factories

            op = MathFactory.getFactory("Add");
            Console.WriteLine(string.Format("{0}: {1}", op.getName(), op.performOperation(2,3)));

            op = MathFactory.getFactory("Sub");
            Console.WriteLine(string.Format("{0}: {1}", op.getName(), op.performOperation(2,3)));

            op = MathFactory.getFactory("Mul");
            Console.WriteLine(string.Format("{0}: {1}", op.getName(), op.performOperation(2,3)));

            op = MathFactory.getFactory("Div");
            Console.WriteLine(string.Format("{0}: {1}", op.getName(), op.performOperation(2,3)));

            // try one more divide that causes error
            Console.WriteLine(string.Format("{0}: {1}", op.getName(), op.performOperation(2,0)));
        }
    } }

输出:

Hello Math Factory!

Addition: 2 + 3 = 5
Subtraction: 2 - 3 = -1
Multiplication: 2 * 3 = 6
Division: 2 / 3 = 0.6666667
Division: 2 / 0 = Divide by zero error

【讨论】:

  • 是的,我确实提供了对属性进行操作的类。我是 c# 和 MVC 的新手,所以如果你有任何关于类工厂的文章可以发给我,那就太好了 :) 我会调查的!我也听说过expandoobject?我只是不知道如何使用它。
【解决方案2】:

ExpandoObject 对您来说可能是个不错的选择。可以如下使用。

dynamic app2    = new ExpandoObject();
app2.Speed      = 2.54d;
app2.Resilience = 99;
app2.Security   = "High";

您可以向已创建的对象添加任意类型的任意数量的属性。

我有一个blog post,其中包含有关ExpandoObject 的更多信息,其中我还讨论了使用反射的替代方法,并且我在 GitHub 上有一个示例项目,它从 JSON 文件中读取动态属性定义和值。

【讨论】:

    猜你喜欢
    • 2013-01-21
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 2021-08-27
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    相关资源
    最近更新 更多