开发者

Implement VB With statement in C#

开发者 https://www.devze.com 2023-01-14 21:46 出处:网络
How would you create an extension method which enables me to do the following 开发者_运维问答(warning: exteme pseudo-code)...

How would you create an extension method which enables me to do the following 开发者_运维问答(warning: exteme pseudo-code)...

class FooBar
{
    Int32 Foo { get; set; }
    String Bar { get; set; }
}

new FooBar().With(fb => new Func<FooBar, Object>(instance =>
{
    // VB With magic
    // NOTE: The instance parameter HAS to be by reference
    instance.Foo = 10;
    instance.Bar;

    return new Object();
}));

If you could specify anonymous functions without a return type (void), the above would look much cleaner...

new FooBar().With(fb => new Func<FooBar, void>(instance =>
{
    instance.Foo = 10;
    instance.Bar;
}));

This is pseudo-code of the worst kind. But I hope you get the idea.


To specify anonymous methods without return type, use Action<T> instead of Func<T, TResult>:

new FooBar().With(new Action<FooBar>(instance =>
{
    instance.Foo = 10;
    instance.Bar;
}));

(I don't quite see the point in this particular case, but I take your word on the pseudo code part...)

Update
Full example for being complete:

The extension method:

public static void With<T>(this T input, Action<T> action)
{
    action(input);
}

Sample usage

new FooBar().With(fb =>
{
    fb.Foo = 10;
    fb.Bar = "some string";
});

Note that you don't need to explicitly declare the Action<FooBar>, the compiler figures that out. Should you wish to, for clarity, the call would look like this:

new FooBar().With<FooBar>(new Action<FooBar>(fb =>
{
    fb.Foo = 10;
    fb.Bar = "some string";
}));


Maybe this will help:

new FooBar().With( fb=> {
    fb.Foo = 10;
    fb.Bar = fb.Foo.ToString();
} );

// ... somewhere else ...
public static void With<T>( this T target, Action<T> action ) {
    action( target );
}


As you asked how to write the extension, here goes

public static void With<T>(this T target, Action<T> action) where T : class
{
   action(target);
}

Personally dont see what benefit this has, but fill yer boots!


How about just

return new FooBar{ Foo=10; };
0

精彩评论

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