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

发布于 2024-12-02 17:58:02 字数 551 浏览 1 评论 0 原文

我已经围绕第 3 方库编写了一个包装类,该类需要通过调用 Config 方法并传递格式为“Property=Value”的字符串来设置属性

。我想在一次调用中传递所有属性并迭代处理它们。

我考虑了以下内容:

  • 创建一个属性/值类,然后创建一个列表 对象
  • 构建由多个“Property=Value”分隔的字符串的 使用令牌(可能是“|”)
  • 使用哈希表

所有这些都可以工作(我正在考虑使用选项 1),但是有更好的方法吗?

有关我的查询的更多详细信息:

完成的类将包含在库中,以便在其他应用程序中重复使用。虽然我目前不认为线程是一个问题(我们的应用程序往往只有一个 UI 线程和一个工作线程),但它将来可能会成为一个问题。

垃圾收集不会成为问题。

目前,访问数据源的任意索引不是问题。

优化目前不是问题,但明确定义键/值对很重要。

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"

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
  • building a string of multiple "Property=Value" separating them
    with a token (maybe "|")
  • Using a hash table

All of these would work (and I'm thinking of using option 1) but is there a better way?

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

迟到的我 2024-12-09 17:58:02

正如您已经指出的,任何建议的解决方案都将完成您所描述的任务。这意味着选择特定方法的唯一合理方法是定义您的需求:

  • 您的代码是否需要支持多个线程同时访问数据源?如果是这样,按照 Yahia 的建议,使用 ConcurrentDictionary 就有意义了。否则,没有理由因为使用并发数据结构而产生额外的开销和复杂性。
  • 您是否在垃圾收集存在问题的环境中工作(例如 XNA 游戏)?如果是这样,任何涉及字符串连接的建议都会有问题。
  • 您是否需要 O(1) 访问数据源的任意索引?如果是这样,你的第三种方法就有意义了。另一方面,如果您所做的只是迭代集合,则没有理由产生插入哈希表的额外开销;请改用 List>
  • 另一方面,您可能没有在需要进行上述优化的环境中工作;以编程方式清晰定义键/值对的能力对您来说可能更重要。在这种情况下,使用字典是更好的选择。

如果没有完全定义功能需要做什么,您就无法就如何实现功能做出明智的决定,并且由于您还没有这样做,所以任何答案这里给出的内容必然是不完整的。

鉴于您的说明,我个人建议如下:

  • 根据 MSDN 指南,默认情况下避免使 Config() 方法成为线程安全的:

    <块引用>

    默认情况下,类库不应该是线程安全的。添加锁来创建线程安全代码会降低性能,增加锁争用,并可能导致发生死锁错误。

  • 如果线程安全稍后变得重要,则使其由调用者负责。

  • 如果您没有特殊的性能要求,请坚持使用字典,以便轻松定义和读取键/值对。

  • 为了简单起见,并避免在连接时生成大量不必要的字符串,只需直接传递字典并迭代它。

考虑以下示例:

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

以及 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
    }
}

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. 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)? 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? 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.
  • 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.

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:

    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:

public void Config(Dictionary<String, String> values)
{
    foreach(var kvp in values)
    {
        var configString = String.Format("{0}={1}", kvp.Key, kvp.Value);
        // do whatever
    }
}
紫南 2024-12-09 17:58:02

您可以使用 Dictionary,然后项目的类型为 KeyValuePair (这对应于您的第一个想法)
然后,您可以使用 myDict.Select(kvp=>string.Format("{0}={1}",kvp.Key,kvp.Value)) 获取字符串列表,其中需要格式化

You could use Dictionary<string,string>, the items are then of type KeyValuePair<string,string> (this correpsonds to your first idea)
You can then use myDict.Select(kvp=>string.Format("{0}={1}",kvp.Key,kvp.Value)) to get a list of strings with the needed formatting

じ违心 2024-12-09 17:58:02

Use for example a ConcurrentDictionary<string,string> - it is thread-safe and really fast since most operations are implemented lock-free...

又怨 2024-12-09 17:58:02

您可以创建一个辅助类,它使用反射将任何类转换为 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 could make a helper class that uses reflection to turn any class into a Property=Value collection

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文