治疗对象属性一样的字典在C# [英] Treat Object Like Dictionary of Properties in C#

查看:112
本文介绍了治疗对象属性一样的字典在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够访问属性值的对象像字典,使用属性作为密钥的名称。我真的不关心,如果该值的返回对象,因此词典<字符串对象> 的罚款。这是预期的用法:

 对象者= {新名称:鲍勃,年龄:45}; 
IDictionary的<字符串对象>查找=新PropertyDictionary(人);
字符串名称=(字符串)人[名称];
的人[时代] =(int)的人[时代] + 1; //潜在的可编辑



我要实现我自己的类这一点,但后来我开始注意到班像DynamicObject实现IDictionary接口,这让觉得这个已经正在为我做的地方。



我要的是类似于ASP.NET MVC使用的功能,允许使用匿名类型来设置HTML标签的属性。我有很多使用字典作为数据源,但大部分时间我应该能够在对象中传递以及类。

由于这是一个一般万用,我以为我会创建一个简单的装饰一个对象IDictionary接口可重复使用的类。这将节省我从创建重载爆炸。


解决方案

我不相信有一个内置的.NET类型像这样的已经在.NET框架。好像你真的想创建一个行为很像一个Javascript对象的对象。如果是的话从 DynamicObject 推导可能是正确的选择。它允许你创建,当裹着对象动态,您可以直接绑定 obj.Name 通过索引或的obj [名称]

 公共类的PropertyBag:DynamicObject { 
私有对象_source;
公众的PropertyBag(对象源){
_source =来源;
}
公共对象的getProperty(字符串名称){
变种类型= _source.GetType();
VAR财产= type.GetProperty(姓名,BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic可);
返回property.GetValue(_source,NULL);
}
公众覆盖布尔TryGetMember(GetMemberBinder粘结剂,out对象的结果){
结果=的getProperty(binder.Name);
返回真;
}
公众覆盖布尔TryGetIndex(GetIndexBinder粘合剂,对象[]索引,出物体的结果){
结果=的getProperty((串)索引[0]);
返回真;
}
}

您可以用它来包装任何类型和同时使用索引和名称语法来获取属性。

  VAR学生=新学生(){名字=约翰,姓氏=母鹿}; 
动态包=新的PropertyBag(学生);
Console.WriteLine(袋[名字]); //输出:约翰
Console.WriteLine(bag.FirstName); //输出:约翰


I want to be able to access property values in an object like a dictionary, using the name of the property as a key. I don't really care if the values are returned as objects, so Dictionary<string, object> is fine. This is the intended usage:

object person = new { Name: "Bob", Age: 45 };
IDictionary<string, object> lookup = new PropertyDictionary(person);
string name = (string)person["Name"];
person["Age"] = (int)person["Age"] + 1; // potentially editable

I was about to implement my own class for this, but then I started noticing classes like DynamicObject implement the IDictionary interface, which made think this was already being done for me somewhere.

What I want is similar to the functionality used by ASP.NET MVC that allows using anonymous types to set HTML tag attributes. I have a lot of classes that use dictionaries as data sources, but most of the time I should be able to pass in objects as well.

Since this is for a general-purpose library, I thought I would create a reusable class that simply decorated an object with the IDictionary interface. It will save me from creating an explosion of overloads.

解决方案

I don't believe there is a built-in .Net type like this already in the .Net framework. It seems like you really want to create an object that behaves a lot like a Javascript object. If so then deriving from DynamicObject may be the right choice. It allows you to create an object which when wrapped with dynamic allows you to bind directly obj.Name or via the indexer obj["Name"].

public class PropertyBag : DynamicObject {
  private object _source;
  public PropertyBag(object source) {
    _source = source;
  }
  public object GetProperty(string name) {  
    var type = _source.GetType();
    var property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
    return property.GetValue(_source, null);
  }
  public override bool TryGetMember(GetMemberBinder binder, out object result) {
    result = GetProperty(binder.Name);
    return true;
  }
  public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) {
    result = GetProperty((string)indexes[0]);
    return true;
  }
}

You can use this to wrap any type and use both the indexer and name syntax to get the properties

var student = new Student() { FirstName = "John", LastName = "Doe" };
dynamic bag = new PropertyBag(student);
Console.WriteLine(bag["FirstName"]);  // Prints: John
Console.WriteLine(bag.FirstName);     // Prints: John

这篇关于治疗对象属性一样的字典在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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