C#实现了有关方式同步的功能

本文关键字:同步 功能 方式 实现 | 更新日期: 2023-09-27 18:20:48

我做了这个:

businessCRM.Description = 
    string.Format("{0}'n" +
             "Name: {1}'n" +
             "Street: {2}'n " +
             "Number: {3}'n" +
             "floor: {4}'n" +
      business.Name,
      business.Address.Street,
      business.Address.Number,
      business.Address.floor,
);

我也想做同样的事情,但相反在其他方法中,比如这样做来进行方式同步(往返):

business.Address.Street = businessCRM.Description;
business.Address.Number = businessCRM.Description;
business.Address.floor = businessCRM.Description;

但我不知道这是否完全正确,知道吗?

C#实现了有关方式同步的功能

真正的解决方案是在businessCRM类中添加一个额外的Address成员,这样您就可以存储数据描述,以后不需要从描述中提取数据。分析它只会导致问题。

您可以使用以下内容将其拆分到字典中;注意,我不得不对第一行(没有前缀)进行特殊处理,如果您的数据在值中包含换行符,则它不会很好地工作:

var parts = new Dictionary<string, string>(
    StringComparer.InvariantCultureIgnoreCase);
string firstLine;
using(var reader = new StringReader(description))
{
    string line;
    firstLine = reader.ReadLine();
    var splitBy = new[] { ':' };
    while ((line = reader.ReadLine()) != null)
    {
        var pair = line.Split(splitBy, 2, StringSplitOptions.None);
        if (pair.Length == 2) parts[pair[0].Trim()] = pair[1].Trim();
    }
}
string tmp;
string name, street, number, floor; // in your case, you could assign to
                                    // the properties directly
name = parts.TryGetValue("Name", out tmp) ? tmp : "";
street = parts.TryGetValue("Street", out tmp) ? tmp : "";
number = parts.TryGetValue("Number", out tmp) ? tmp : "";
floor = parts.TryGetValue("floor", out tmp) ? tmp : "";

首先请参阅有问题的@Marc Gravell评论-处理"反序列化"会容易得多。如果没有,这里有解决方案。

  1. 我的代码可能很慢-你需要缓存反射信息(比如属性信息收集)
  2. 没有错误处理和检查(例如,无效-手动执行;)
  3. 代码假定输入始终是正确的输入(例如值内的换行符)、格式等

代码:

var addressType = business.Address.GetType();
foreach (var line in businessCRM.Description
                                .Split(new[] { "'n", Environment.NewLine },
                                              StringSplitOptions.RemoveEmptyEntries))
{
    var propSelectorIndex = line.IndexOf(":");
    if (propSelectorIndex == -1) continue;
    var propName = line.Subtring(0, propSelectorIndex);
    var propInfo = addressType.GetProperties(BindigsFlag.Public 
                                                      | BindigsFlag.Instance)
                              .FirstOrDefault(prop => prop.Name == propName);
    if (propInfo == null) throw new InvalidOperationException();
    var newPropValue = line.Substring(propSelectorIndex + 2); 
                 // + 2 to omit : char and additional space
    propInfo.SetValue(business.Address, newPropValue, null);
}