【问题标题】:Issue with String Extension in C# [duplicate]C#中的字符串扩展问题[重复]
【发布时间】:2017-02-07 07:18:59
【问题描述】:

我正在尝试制作一个简单的字符串扩展,将更改分配给原始字符串(如 toUpper)。在这种情况下,如果第二个参数既不是空格也不是空值,该方法会将内容分配给...否则,它将保留当前值,或将空值分配给“”。所以,我想让它去:

somerecord.Property1.func(someobj.property);
somerecord.Property2.func(someobj.otherproperty);
somerecord.Property3.func(someobj.anotherproperty);

虽然我的代码看起来像

    public static string func(this String str, string replacement)
    {
        if (!String.IsNullOrWhiteSpace(replacement)) {
            str = replacement;
            return replacement;
        }
        else
        {
            if(str == null)
              str = "";
            return "";
        }
    }

我想将this 设置为ref,但我不能。关于如何干净地实现这一点的任何想法?

【问题讨论】:

  • 我相当肯定没有办法做到这一点。不能ref this(即不能修改变量)也不能修改字符串实例。
  • @ThomasD。扩展方法可以与 null 完美配合,不确定您想说什么。
  • Thomas D.,如果我创建的对象 obj 具有未定义的属性字符串 s,那么 obj.s.func(something) 会将字符串显示为 null。 Michael Gunter,ToLower 和 ToUpper 这样的方法是如何工作的呢?
  • 他们返回一个副本,但不修改原始字符串。有关 ToUpper 的示例,请参见此处 (msdn.microsoft.com/en-us/library/ewdd6aed(v=vs.110).aspx)。特别是,从该链接“此方法不会修改当前实例的值。相反,它返回一个新字符串,其中当前实例中的所有字符都转换为大写。”。
  • 旁注:@user3856804 我会 edit 指出问题的“更改原始字符串(如 toUpper)”部分 - 没有充分的理由包含可以立即验证为的语句通过查看文档是错误的。作为投票磁铁,我不会感到惊讶。

标签: c# string extension-methods


【解决方案1】:

不要使方法成为扩展方法,实现常规静态方法:

public static void func(ref string str, string replacement)
{
    if (!String.IsNullOrWhiteSpace(replacement)) {
        str = replacement;
    }
    else
    {
        if(str == null)
          str = "";
    }
}

但请注意,您的用例仍然无法正常工作,您不能将属性作为 ref 参数传递:

class Foo
{
    public string someVariable;
    public string SomeProperty { get; }
}

var foo = new Foo();
func(ref foo.someVariable, ""); //ok
func(ref foo.SomeProperty, ""); //compile time error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    相关资源
    最近更新 更多