动态地向类添加属性

时间:2018-11-26 14:08:35

标签: c# dynamic properties

动态创建类属性的最佳方法是什么?

我必须基于Webhook推送消息创建JSON数据。 我创建了2个类,每个类都有多个属性,问题是,即使未填充属性(默认情况下为NULL),webhook push的格式也错误。为了避免这种情况,我必须根据需要创建属性。

是否有任何方法可以做到这一点? 描绘我需要的东西:

public class ChannelSettings
{
    public string channel { get; set; }
    public string username { get; set; }
    public string text { get; set; }
    public AttachSettings attachments { get; set; } //Here I would like to this property to be dynamic
}

public class AttachSettings
{
    public string fallback { get; set; }
    public string pretext { get; set; }
    public string text { get; set; }
    public string title { get; set; }
    public string author_name { get; set; }
    public string image_url { get; set; }
    public string author_icon { get; set; }
}
public string GenJSON(ChannelSettings channelSet)
{
    string output = JsonConvert.SerializeObject(channelSet);
    return output;
}

6 个答案:

答案 0 :(得分:0)

您可以使用ExpandoObject

    dynamic expandoObject = new ExpandoObject();
    expandoObject.NewProperty =  "newValue";

我认为example可以帮助您。

答案 1 :(得分:0)

我不知道我是否理解正确,但是为什么不将此属性设为可选? 只是使用AttachSettings?一切都应该没事。

答案 2 :(得分:0)

您真正想要的是让c成为字典还是其他东西?:

AttachSettings

这应该产生如下的JSON:

public class ChannelSettings
{
    public string channel { get; set; }
    public string username { get; set; }
    public string text { get; set; }
    public Dictionary<string, string> attachments { get; set; } 
}

public ChannelSettings GetData()
{
    return new ChannelSettings
    {        
        channel="one", username="user", text="text",
        attachments= new Dictionary<string, string>()
        {
            {"fallback","somevalue"},
            {"author_name","some author"},
            {"shoe_size","12},
            //...etc...
        }
    }
}

public string GenJSON(ChannelSettings channelSet)
{
    string output = JsonConvert.SerializeObject(channelSet);
    return output;
}

答案 3 :(得分:0)

您可以将参数类型设置为动态,并对其进行序列化和反序列化,如下所示:

    {
  "name": "admin-managment-barber",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@babel/core": "7.1.0",
    "@svgr/webpack": "2.4.1",
    "babel-core": "7.0.0-bridge.0",
    "babel-eslint": "9.0.0",
    "babel-jest": "23.6.0",
    "babel-loader": "8.0.4",
    "babel-plugin-named-asset-import": "^0.2.3",
    "babel-preset-react-app": "^6.1.0",
    "bfj": "6.1.1",
    "case-sensitive-paths-webpack-plugin": "2.1.2",
    "chalk": "2.4.1",
    "css-loader": "1.0.0",
    "dotenv": "6.0.0",
    "dotenv-expand": "4.2.0",
    "eslint": "5.6.0",
    "eslint-config-react-app": "^3.0.5",
    "eslint-loader": "2.1.1",
    "eslint-plugin-flowtype": "2.50.1",
    "eslint-plugin-import": "2.14.0",
    "eslint-plugin-jsx-a11y": "6.1.2",
    "eslint-plugin-react": "7.11.1",
    "file-loader": "2.0.0",
    "fork-ts-checker-webpack-plugin-alt": "0.4.14",
    "fs-extra": "7.0.0",
    "html-webpack-plugin": "4.0.0-alpha.2",
    "identity-obj-proxy": "3.0.0",
    "jest": "23.6.0",
    "jest-pnp-resolver": "1.0.1",
    "jest-resolve": "23.6.0",
    "mini-css-extract-plugin": "0.4.3",
    "mobx": "^5.6.0",
    "mobx-react": "^5.4.2",
    "mobx-react-router": "^4.0.5",
    "moment": "^2.22.2",
    "optimize-css-assets-webpack-plugin": "5.0.1",
    "pnp-webpack-plugin": "1.1.0",
    "postcss-flexbugs-fixes": "4.1.0",
    "postcss-loader": "3.0.0",
    "postcss-preset-env": "6.0.6",
    "postcss-safe-parser": "4.0.1",
    "react": "^16.6.3",
    "react-app-polyfill": "^0.1.3",
    "react-dev-utils": "^6.1.1",
    "react-dom": "^16.6.3",
    "react-router-dom": "^4.3.1",
    "resolve": "1.8.1",
    "sass-loader": "7.1.0",
    "style-loader": "0.23.0",
    "terser-webpack-plugin": "1.1.0",
    "url-loader": "1.1.1",
    "webpack": "4.19.1",
    "webpack-dev-server": "3.1.9",
    "webpack-manifest-plugin": "2.0.4",
    "workbox-webpack-plugin": "3.6.3"
  },
  "scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,ts,tsx}",
      "!src/**/*.d.ts"
    ],
    "resolver": "jest-pnp-resolver",
    "setupFiles": [
      "react-app-polyfill/jsdom"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
      "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,ts,tsx}"
    ],
    "testEnvironment": "jsdom",
    "testURL": "http://localhost",
    "transform": {
      "^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$",
      "^.+\\.module\\.(css|sass|scss)$"
    ],
    "moduleNameMapper": {
      "^react-native$": "react-native-web",
      "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "web.ts",
      "ts",
      "web.tsx",
      "tsx",
      "json",
      "web.jsx",
      "jsx",
      "node"
    ]
  },
  "babel": {
    "plugins": [
      [
        "@babel/plugin-proposal-decorators",
        {
          "legacy": true
                }
      ],
      [
        "@babel/plugin-proposal-class-properties",
        {
          "loose": true
        }
      ]
    ],
    "presets": [
      "react-app"
    ]
  },
  "devDependencies": {
    "@babel/plugin-proposal-class-properties": "^7.1.0",
    "@babel/plugin-proposal-decorators": "^7.1.6",
    "@babel/plugin-transform-react-jsx-source": "^7.0.0"
  }
}

输出为:test

@GPW还有另一种使用字典的解决方案,该字典适用于未知类型/参数大小。

答案 4 :(得分:0)

我能想到的最接近的是ExpandoObject。它似乎可以与任何弱类型的WebService一起使用,并且您确实提到了JSON。

内部的似乎只不过是Dictionary<string, object>加上一些语法糖,更改名词和隐式转换而已。因此,如果有疑问,您也可以使用一个很好的旧收藏集。

答案 5 :(得分:0)

感谢所有非常有用的帮助,我已经解决了我的问题,该案例是Channel Class内部的Attachment的一个实例,我必须创建它的列表:

public class ChannelSettings
{
    public string channel { get; set; }
    public string username { get; set; }
    public string text { get; set; }
    public List<AttachSettings> attachments { get; set; }

} 

然后不执行它,如果在这种情况下value为空,我会得到想要的结果。

“ {”频道“:空,”用户名“:”用户“,”文本“:”测试文本“,”附件“:空}”

在开始时我想要的有点不同,但是它的作用相同,所以不需要进一步更改:)

相关问题