c# - 在C#中实现VB With语句

标签 c# vb.net

您将如何创建一种扩展方法,使我能够执行以下操作(警告:exteme伪代码)...

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();
}));


如果您可以指定没有返回类型(void)的匿名函数,那么上面的代码看起来会更干净...

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


这是最糟糕的伪代码。但我希望你能明白。

最佳答案

也许这会有所帮助:

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 );
}

关于c# - 在C#中实现VB With语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3634214/

相关文章:

c# - 为什么 ManualResetEventSlim.Wait 似乎不会在整个等待时间内阻塞?

c# - 从内部调用安全的 ServiceStack 服务

mysql - Entity Framework 添加不应通过其他对象添加的数据

c# - LINQ - 嵌套计数问题

c# - .Net MVC4 文化设置正确,但验证仍然是英语

c# - Dictionary.ContainsKey() - 它是如何工作的?

c# - 通过 EnvDTE 以编程方式更改 Visual Studio 项目的调试属性

vb.net - 多线程应用程序中的 System.ObjectDisposedException

c# - "managed"代码到底是什么?

vb.net - 日期时间格式字符串?