简体   繁体   English

将值添加到对象类型c#

[英]Add value to object type c#

I've have object like this: 我有这样的对象:

object rt = new {
    page = 1,
};

Now how could I add new values to this object? 现在我怎么能为这个对象添加新值? I mean something like this: 我的意思是这样的:

rt += { code = 5 };

How it could be possible? 怎么可能?

It sounds more like you want a Dictionary<string,int> 听起来更像是你想要一个Dictionary<string,int>

var rt =  new Dictinary<string,int>(){
    {"page",1}
};

rt.Add("code",5);

You can also do it with System.Dynamic.ExpandoObject - but this is just a fancy wrapper around a dictionary. 您也可以使用System.Dynamic.ExpandoObject来完成它 - 但这只是一个围绕字典的奇特包装器。

dynamic rt = new ExpandoObject();
rt.page = 1;
rt.code = 5;

Console.WriteLine(rt.page);

Use ExpandoObject 使用ExpandoObject

 dynamic rt = new ExpandoObject();
 rt.page = 1;
 rt.code = 5;

The actual question is: why do you need this at all? 实际的问题是:为什么你需要这个? Imagine your object was a named one, eg like this: 想象一下你的对象是一个命名对象,例如:

var m = new MyClass { MyProperty = ... };

with

class MyClass
{
    public string MyProperty;
}

What you want to do is, to add a further property to that class at runtime, which isn´t possible. 你想要做的是,在运行时向该类添加另一个属性,这是不可能的。 You can´t do the following: 你不能做以下事情:

m.AnotherProperty = ...

as AnotherProperty isn´t defined on that type. 因为AnotherProperty在该类型上定义。

Even declaring m as dynamic wouldn´t help you, as the actual type ( MyClass ) doesn´t know anything of AnotherProperty . 即使将m声明为dynamic也不AnotherProperty你有帮助,因为实际类型( MyClass )不知道AnotherProperty任何内容。

dynamic a = new MyClass { MyProperty = ... };
a.AnotherProperty = ...;

So the simple answer to your question is: no, you can´t add members to a class at runtime. 所以对你的问题的简单回答是: 不,你不能在运行时向成员添加成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM