【问题标题】:Replace string value with extension method [duplicate]用扩展方法替换字符串值[重复]
【发布时间】:2016-10-15 10:16:39
【问题描述】:

所以我基本上在做的是解析消息(HL7 标准)。

有时这些 HL7 消息包含一个“完整”记录,其中包含所有信息,有时其中只有更新的部分。

这是一行数据的示例。假设这一行包含一些患者/客户信息,例如姓名、出生日期等。它可能如下所示:

|Mike|Miller|19790530|truck driver|blonde|m|

其中的列实际上代表了这一点:

|first name|surname|date of birth|job|hair color|gender|

现在这是一整行数据。

更新可能如下所示(他结婚、失业并改变了头发颜色):

||O'Connor||""|brown||

其中""代表工作列的值,brown代表他头发颜色的变化。

在 HL7 标准中规定,省略字段(例如名字或性别)意味着没有进行任何更改,而 "" 表示该字段中的数据已被删除。具有值的字段可能需要更新。所以我的名字的更新逻辑看起来与此类似(pidEntity 是一个数据库对象,不是先创建代码,而是先创建数据库,pidEntity.FirstName 是一个属性)

var pid = this.message.PID; // patient identification object from parsed message
if (pid.PatientName.GivenName.Value == string.Empty)
{
    // "" => deletion flag
    pidEntity.FirstName = null;
}
else if (pid.PatientName.GivenName.Value == null)
{
    // omitted, no changes
    return;
}
pidEntity.FirstName = pid.PatientName.GivenName.Value;

我做了很多这样的字符串更新,所以我想嘿-为什么不尝试使用扩展方法或带有ref参数的方法。

我的第一次尝试是这样的:

// doesn't work because strings are immutable
public static void Update(this string @this, string newValue)
{
    if (newValue == string.Empty) @this = null;
    else if (newValue == null) return;
    @this = newValue;
}

// usage
pidEntity.FirstName.Update(pid.PatientName.GivenName.Value);

将第一个参数更改为this ref string @this 也不起作用。 outref 的更新函数也没有,因为属性不能像这样作为 ref 或 out 参数传递:

public static void Update(ref string property, string newValue)
// usage
Update(pidEntity.FirstName, pid.PatientName.GivenName.Value);

到目前为止,我能想到的最“优雅”的就是这个,忽略 "" 意味着将数据库对象的值设置为 null 并将其设置为空字符串这一事实。

pidEntity.FirstName = pid.PatientName.GivenName.Value ?? pidEntity.FirstName;

我的另一个解决方案是这样的扩展方法:

public static void UpdateString(this string hl7Value, Action<string> updateAct)
{
    if (updateAct == null) throw new ArgumentNullException(nameof(updateAct));

    if (hl7Value == string.Empty) updateAct(null);
    else if (hl7Value == null) return;
    updateAct(hl7Value);
}
// usage
pid.PatientName.GivenName.Value.UpdateString(v => pidEntity.FirstName = v);

我认为必须有一个更简单的方法,但我需要你的帮助(也许是反射?):)

【问题讨论】:

  • 好问题。由于它本质上归结为“如何将属性作为 ref 参数传递”(我看不到您的问题的另一种解决方案),因此我冒昧地将您的问题标记为另一个问题的副本,这解释了所有解决方法目前已知。如果您不同意,请告诉我,我会重新打开它。
  • 我同意你的看法,这是一个非常好的答案——正是我想要的。我想知道我怎么从来没有在谷歌上找到它。我怀疑还有一种反射方式,我个人最喜欢的是带有表情的方式。

标签: c# extension-methods


【解决方案1】:

字符串为immutable - 您可以创建新字符串,但不能更新字符串的现有实例。

【讨论】:

    猜你喜欢
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    相关资源
    最近更新 更多