如何当你有这个名字在另一个变量设置C#4动态对象的属性 [英] How to set a property of a C# 4 dynamic object when you have the name in another variable

查看:141
本文介绍了如何当你有这个名字在另一个变量设置C#4动态对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一种方式来修改一个动态仅在运行时称为属性的名称C#4.0对象的属性。

I'm looking for a way to modify properties on a dynamic C# 4.0 object with the name of the property known only at runtime.

有没有办法做这样的事情( ExpandoObject 只是用来作为一个例子,这可能是任何类实现 IDynamicMetaObjectProvider ):

Is there a way to do something like (ExpandoObject is just used as an example, this could be any class that implements IDynamicMetaObjectProvider):

string key = "TestKey";
dynamic e = new ExpandoObject();
e[key] = "value";

这将等同于:

Which would be equivalent to:

dynamic e = new ExpandoObject();
e.TestKey = "value";

或者是唯一的出路思考?

Or is the only way forward reflection?

推荐答案

不是很容易,没有。反思是不行的,因为它假设一个普通类型的模型,这是的没有的全方位动力。如果你实际上只是说话有规则物体,那么就使用反射在这里。否则,我希望你可能要反向工程,code编译器会发出一个基本的分配和调整它有一个灵活的成员名称。我会说实话,虽然:这不是一个有吸引力的选择;一个简单的:

Not very easily, no. Reflection doesn't work, since it assumes a regular type model, which is not the full range of dynamic. If you are actually just talking to regular objects, then just use reflection here. Otherwise, I expect you may want to reverse-engineer the code that the compiler emits for a basic assignment, and tweak it to have a flexibly member-name. I'll be honest, though: this isn't an attractive option; a simple:

dynamic foo = ...
foo.Bar = "abc";

语句:

if (<Main>o__SiteContainer0.<>p__Site1 == null)
{
    <Main>o__SiteContainer0.<>p__Site1 = CallSite<Func<CallSite, object, string, object>>.Create(Binder.SetMember(CSharpBinderFlags.None, "Bar", typeof(Program), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant | CSharpArgumentInfoFlags.UseCompileTimeType, null) }));
}
<Main>o__SiteContainer0.<>p__Site1.Target(<Main>o__SiteContainer0.<>p__Site1, foo, "abc");


如果你想要一个,工程动态和非动态对象的方法: FastMember 是得心应手了这一点,工作在任一类型或对象级别:


If you want an approach that works for both dynamic and non-dynamic objects: FastMember is handy for this, and works at either the type or object level:

// could be static or DLR 
var wrapped = ObjectAccessor.Create(obj); 
string propName = // something known only at runtime 
Console.WriteLine(wrapped[propName]);

提供的NuGet,以及大量的动态和非动态的场景进行了优化。

available on Nuget, and heavily optimised for both dynamic and non-dynamic scenarios.

这篇关于如何当你有这个名字在另一个变量设置C#4动态对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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