如何在C#类中添加动态属性 [英] How to add Dynamic Properties in a Class C#
本文介绍了如何在C#类中添加动态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
如何通过传递的参数数组动态生成类属性.如下所示,可以给我一个简单的例子
Hi All,
How to generate class properties dynamically with array of parameters passed. Something like below, can any give me good and simple example
[WebMethod]
public static object LoadData(NameValue[] dtdata)
{
// Creating a dynamic dictionary.
dynamic dt = new DynamicDictionary();
foreach (var value1 in dtdata)
{
var key = value1.name;
dt.key = value1.value; // this is error
//should be something like dt.Firstname, I need to loop around each parameter and create the same as property
}
return dt;
}
基本上,我应该返回具有所有生成的属性的对象. (就像具有点运算符可访问性的普通对象一样)
在Advance中感谢
basically I should return object with all the generated properties. (just like normal object which has dot operator accessibility)
Thanks in Advance
推荐答案
查看System.CodeDom
命名空间.在那里,您会发现许多用于动态生成代码的类(带有方法和属性的类).
但是,在使用新生成的类时,我建议它们应该实现一些接口,否则您将不得不使用反射来访问它们.
Look at theSystem.CodeDom
namespace. There you''ll find many classes for generating code (classes with methods and properties) dynamically.
But when it comes to using your freshly generated classes, I do recommend that they should implement some interface(s), otherwise you''ll have to use reflection to access them.
这篇关于如何在C#类中添加动态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文