将值添加到对象类型 c# [英] Add value to object type c#

查看:56
本文介绍了将值添加到对象类型 c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的对象:

object rt = new {
    page = 1,
};

现在我如何向这个对象添加新值?我的意思是这样的:

Now how could I add new values to this object? I mean something like this:

rt += { code = 5 };

怎么可能?

推荐答案

实际的问题是:你为什么需要这个?想象一下你的对象是一个命名对象,例如像这样:

The actual question is: why do you need this at all? Imagine your object was a named one, e.g. like this:

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

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 未在该类型上定义.

as AnotherProperty isn´t defined on that type.

即使将 m 声明为 dynamic 也无济于事,因为 actual 类型 (MyClass) 不会对AnotherProperty一无所知.

Even declaring m as dynamic wouldn´t help you, as the actual type (MyClass) doesn´t know anything of 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.

这篇关于将值添加到对象类型 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆