简体   繁体   English

实现property = value集合的最佳方法是什么

[英]What is the best way to implement a property=value collection

I've written a wrapper class around a 3rd party library that requires properties to be set by calling a Config method and passing a string formatted as " Property=Value " 我已经围绕第三方库编写了一个包装类,它需要通过调用Config方法并传递格式为“ Property = Value ”的字符串来设置属性。

I'd like to pass all the properties in a single call and process them iteratively. 我想在一次调用中传递所有属性并迭代地处理它们。

I've considered the following: 我考虑过以下几点:

  • creating a property/value class and then creating a List of these objects 创建属性/值类,然后创建这些对象的List
  • building a string of multiple " Property=Value " separating them with a token (maybe "|") 构建一个多个“ Property = Value ”的字符串,用一个标记分隔它们(可能是“|”)
  • Using a hash table 使用哈希表

All of these would work (and I'm thinking of using option 1) but is there a better way? 所有这些都可行(我正在考虑使用选项1)但是有更好的方法吗?

A bit more detail about my query: 关于我的查询的更多细节:

The finished class will be included in a library for re-use in other applications. 完成的类将包含在库中,以便在其他应用程序中重用。 Whilst I don't currently see threading as a problem at the moment (our apps tend to just have a UI thread and a worker thread) it could become an issue in the future. 虽然我目前没有将线程视为一个问题(我们的应用程序往往只有一个UI线程和一个工作线程),但它可能会成为未来的问题。

Garbage collection will not be an issue. 垃圾收集不会成为问题。

Access to arbitrary indices of the data source is not currently an issue. 目前,访问数据源的任意索引不是问题。

Optimization is not currently an issue but clearly define the key/value pairs is important. 优化目前不是问题,但明确定义键/值对很重要。

您可以使用Dictionary<string,string> ,这些项目的类型为KeyValuePair<string,string> (这与您的第一个想法相对应)您可以使用myDict.Select(kvp=>string.Format("{0}={1}",kvp.Key,kvp.Value))获取具有所需格式的字符串列表

As you've already pointed out, any of the proposed solutions will accomplish the task as you've described it. 正如您已经指出的那样,任何提议的解决方案都将完成您所描述的任务。 What this means is that the only rational way to choose a particular method is to define your requirements: 这意味着选择特定方法的唯一合理方法是定义您的要求:

  • Does your code need to support multiple threads accessing the data source simultaneously? 您的代码是否需要支持同时访问数据源的多个线程? If so, using a ConcurrentDictionary , as Yahia suggested, makes sense. 如果是这样的话,正如Yahia所建议的,使用ConcurrentDictionary是有道理的。 Otherwise, there's no reason to incur the additional overhead and complexity of using a concurrent data structure. 否则,没有理由引起使用并发数据结构的额外开销和复杂性。
  • Are you working in an environment where garbage collection is a problem (for example, an XNA game)? 您是否在垃圾收集存在问题的环境中工作(例如,XNA游戏)? If so, any suggestion involving the concatenation of strings is going to be problematic. 如果是这样,任何涉及字符串串联的建议都将成为问题。
  • Do you need O(1) access to arbitrary indices of the data source? 您是否需要O(1)访问数据源的任意索引? If so, your third approach makes sense. 如果是这样,你的第三种方法是有道理的 On the other hand, if all you're doing is iterating over the collection, there's no reason to incur the additional overhead of inserting into a hashtable; 另一方面,如果您所做的只是迭代集合,则没有理由承担插入哈希表的额外开销; use a List<KeyValuePair<String, String>> instead. 请改用List<KeyValuePair<String, String>>
  • On the other hand, you may not be working in an environment where the optimization described above is necessary; 另一方面,您可能无法在需要上述优化的环境中工作; the ability to clearly define the key/value pairs programatically may be more important to you. 以编程方式清楚地定义键/值对的能力对您来说可能更重要。 In which case using a Dictionary is a better choice. 在这种情况下使用Dictionary是一个更好的选择。

You can't make an informed decision as to how to implement a feature without completely defining what the feature needs to do , and since you haven't done that, any answer given here will necessarily be incomplete. 如果没有完全定义功能需要 执行的功能,您无法做出如何实现功能的明智决定,并且由于您没有这样做,因此此处给出的任何答案都必然是不完整的。

Given your clarifications, I would personally suggest the following: 鉴于您的澄清,我个人会建议如下:

  • Avoid making your Config() method thread-safe by default, as per the MSDN guidelines: 根据MSDN指南,默认情况下避免使Config()方法成为线程安全的:

    By default, class libraries should not be thread safe. 默认情况下,类库不应该是线程安全的。 Adding locks to create thread-safe code decreases performance, increases lock contention, and creates the possibility for deadlock bugs to occur. 添加锁以创建线程安全的代码会降低性能,增加锁争用,并且可能会发生死锁错误。

  • If thread safety becomes important later, make it the caller's responsibility. 如果线程安全性在以后变得重要,请将其作为调用者的责任。

  • Given that you don't have special performance requirements, stick with a dictionary to allow key/value pairs to be easily defined and read. 鉴于您没有特殊的性能要求,请坚持使用字典以便轻松定义和读取键/值对。

  • For simplicity's sake, and to avoid generating lots of unnecessary strings doing concatenations, just pass the dictionary in directly and iterate over it. 为简单起见,为避免生成大量不必要的字符串进行连接,只需直接传递字典并迭代它。

Consider the following example: 请考虑以下示例:

var configData = new Dictionary<String, String>
configData["key1"] = "value1";
configData["key2"] = "value2";
myLibraryObject.Config(configData);

And the implementation of Config: 并且Config的实现:

public void Config(Dictionary<String, String> values)
{
    foreach(var kvp in values)
    {
        var configString = String.Format("{0}={1}", kvp.Key, kvp.Value);
        // do whatever
    }
}

例如,使用ConcurrentDictionary<string,string> - 它是线程安全且非常快,因为大多数操作都是无锁实现的......

You could make a helper class that uses reflection to turn any class into a Property=Value collection 您可以创建一个使用反射的帮助程序类,将任何类转换为Property = Value集合

public static class PropertyValueHelper
{
     public static IEnumerable<string> GetPropertyValues(object source)
     { 
          Type t = source.GetType();

          foreach (var property in t.GetProperties())
          {
               object value = property.GetValue(source, null);
               if (value != null)
               {
                    yield return property.Name + "=" + value.ToString();
               }
               else
               {
                    yield return property.Name + "=";  
               }
          }
     } 
}

You would need to add extra logic to handle enumerations, indexed properties, etc. 您需要添加额外的逻辑来处理枚举,索引属性等。

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

相关问题 实现对公众只读的属性,但对继承者可写的最佳方法是什么? - What is the best way to implement a property that is readonly to the public, but writable to inheritors? 在C#对象中实现动态属性的最佳方法是什么? - What is the best way to implement dynamic property in a C# object? 为基础 class 实现必须设置属性的最佳方法是什么? - What is the best way to implement a Must Set Property for a Base class? 使用LINQ为集合中的所有对象的属性赋值的最佳方法 - Best way to assign a value to a property of all objects in a collection using LINQ 获得具有特定属性的属性和值的最佳方法是什么? - What is the best way to get a property and value with a particular attribute? 在c#中实现队列的最佳方法是什么(System.Collection.Queue有内存限制) - What is best way to implement a queue in c#(System.Collection.Queue has memory limitation) 使用具有Collection属性的LINQ to Entities的最佳方法 - Best way to use LINQ to Entities with a Collection Property 声明属性的最佳方法是什么 - what the best way to declare a property 按季度计算日期收集的最佳方法是什么? - What is the best way to count collection of dates by quarter? 实现预计算数据的最佳方式是什么? - What is the best way to implement precomputed data?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM