开发者

Self-reference object in chained method calls

开发者 https://www.devze.com 2023-03-12 00:23 出处:网络
How do you reference the chained method\'s object in that same method\'s arguments. Let\'s say you have a number of chained method calls that trim/substring a string like so:

How do you reference the chained method's object in that same method's arguments. Let's say you have a number of chained method calls that trim/substring a string like so:

str.Substring(varLen1).Substring(varLen2).Substring(1,##self##.Length-2)

The problem is that becau开发者_开发百科se the length of the string is now unknown and different from the original string's length, how do I substring like in the last call (a substring where the index and length may depend on the string itself).

Thanks!


In short, no.

Though with an extension method you could capture ##self## and use a lambda to continue the expression.

public static TResult WithSelf<TSource, TResult> (this TSource x, Func<TSource, TResult> f)
{
    return f (x);
}

str.Substring (STDIN_PFX_FN.Length)
    .Trim (new char[] {'"', ' '})
    .WithSelf (x => x.Substring (1, x.Length - 2))

I tend to think that ends up more complicated to read and uglier and simply prefer to create a separate function.

str = Clean(str);

private string Clean (string str)
{
    str = str.Substring (STDIN_PFX_FN.Length).Trim (new char[] {'"', ' '});
    return str.Substring (1, str.Length - 2);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消