标签: anonymous-methods

在匿名方法中使用MethodInfo.GetCurrentMethod()

public static void Main(string[] args)
{
    Action a = () => Console.WriteLine(MethodInfo.GetCurrentMethod().Name);
    a();
}
Run Code Online (Sandbox Code Playgroud)

这段代码将返回一个不起眼的字符串,如下所示:<Main>b__0.

有没有办法忽略匿名方法并获得更易读的方法名称?

.net c# reflection anonymous-methods

7
推荐指数
2
解决办法
4121
查看次数

声明Func <in T,out Result>动态

考虑一下:

var propertyinfo = typeof(Customer).GetProperty(sortExpressionStr);
Type orderType = propertyinfo.PropertyType;
Run Code Online (Sandbox Code Playgroud)

现在我想宣布

Func<int,orderType>
Run Code Online (Sandbox Code Playgroud)

我知道它不可能直接ordertype在运行时,但有任何解决方法吗?

这正是我想要做的:

var propertyinfo = typeof(T).GetProperty(sortExpressionStr);
Type orderType = propertyinfo.PropertyType;

var param = Expression.Parameter(typeof(T), "x");
var sortExpression = (Expression.Lambda<Func<T, orderType>>
   (Expression.Convert(Expression.Property(param, sortExpressionStr), typeof(orderType)), param));
Run Code Online (Sandbox Code Playgroud)

这一切都是因为我想转换:

Expression<Func<T,object>> to Expression<Func<T,orderType>>
Run Code Online (Sandbox Code Playgroud)

或者如果它不可能那么我想从正确的类型的第一个地方创建它,案例如下:

我在一个方法中,它有一个type(Customer)和我想要通过它订购的类型的属性名称,我想创建一个排序表达式树来将它传递给Orderby(这里).

c# lambda predicate anonymous-methods expression-trees

6
推荐指数
3
解决办法
5405
查看次数

如何避免"动态"事件订阅中的匿名方法?

我怎么能重构这个方法

private void ListenToPropertyChangedEvent(INotifyPropertyChanged source,
                                          string propertyName)
{
    source.PropertyChanged += (o, e) =>
    {
        if (e.PropertyName == propertyName)
            MyMagicMethod();
    };
}
Run Code Online (Sandbox Code Playgroud)

如果我想避免在这里使用匿名方法?

c# anonymous-methods

6
推荐指数
1
解决办法
436
查看次数

用于生成共享相同闭包变量的匿名委托的C#技术

我有一种情况需要生成一些类似的匿名代表.这是一个例子:

public void Foo(AnotherType theObj)
{
    var shared = (SomeType)null;

    theObj.LoadThing += () =>
    {
        if(shared == null)
            shared = LoadShared();

        return shared.Thing;
    };

    theObj.LoadOtherThing += () =>
    {
        if(shared == null)
            shared = LoadShared();

        return shared.OtherThing;
    };

    // more event handlers here...
}
Run Code Online (Sandbox Code Playgroud)

我遇到的麻烦是我的代码不是很干.每个事件处理程序的内容非常相似,可以很容易地参数化为工厂方法.阻止我这样做的唯一因素是每个委托需要共享对shared变量的引用.我无法shared使用ref关键字传递给工厂方法,因为您无法围绕ref变量创建闭包.有任何想法吗?

c# lambda anonymous-methods

6
推荐指数
1
解决办法
512
查看次数

linq匿名方法中的局部变量范围(闭包)

Linq Query中声明的局部变量的范围是什么.

我正在编写以下代码

   static void Evaluate()
    {
        var listNumbers = Enumerable.Range(1, 10).Select(i => i);
        int i = 10;
    }
Run Code Online (Sandbox Code Playgroud)

编译器标记的错误在行int i = 10,说明

A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else 
Run Code Online (Sandbox Code Playgroud)

我无法理解为什么会出现这个错误.

我的理解是,i在第一行之后(在foreach循环中)将超出范围.所以i可以再次宣布.

实际行为是i在第一行(在foreach循环中)之后无法访问,这是正确的.但i不能再宣布.这看起来很奇怪.

编辑这是基于安德拉斯的回应的以下问题.答案非常好,但会引起进一步的质疑.

  static void Evaluate3()
    {
        var listNumbers = Enumerable.Range(1, 10).Select(i => i);
        var listNumbers1 …
Run Code Online (Sandbox Code Playgroud)

.net c# linq closures anonymous-methods

6
推荐指数
1
解决办法
1256
查看次数

如何知道Action是否是匿名方法?

这是C#4.0.

我有一类商店WeakReference的一些作者Action,就好比:

public class LoremIpsum
{
    private Dictionary<Type, List<WeakReference>> references = new Dictionary<Type, List<WeakReference>>();

    public void KeepReference<T>(Action<T> action)
    {
        if (this.references.ContainsKey(typeof(T)))
        {
            this.references[typeof(T)].Add(new WeakReference(action));
        }
        else
        {
            this.references.Add(typeof(T), new List<WeakReference> { new WeakReference(action) });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这个类有另一个允许执行Action稍后传递给它的方法,但在这个问题中它并不重要.

我以这种方式使用这个类:

public class Foobar
{
    public Bar Bar { get; set; }

    public void Foo(LoremIpsum ipsum)
    {
        ipsum.KeepReference<Bar>((b) => { this.Bar = b; });
        ipsum.KeepReference<Bar>(this.Whatever);
    }

    public void Whatever(Bar bar)
    {
        // Do anything, for example...: …
Run Code Online (Sandbox Code Playgroud)

c# delegates anonymous-methods

6
推荐指数
1
解决办法
1056
查看次数

匿名方法如何省略参数列表?

我在关于匿名方法(C#编程指南)的MSDN文档中阅读本文,但我不理解省略参数列表的部分.它说:

有一种情况是匿名方法提供lambda表达式中找不到的功能.匿名方法使您可以省略参数列表.这意味着可以将匿名方法转换为具有各种签名的委托.lambda表达式无法做到这一点.

你能举一个省略匿名方法参数列表的例子吗?

c# lambda anonymous-methods anonymous-function

6
推荐指数
1
解决办法
804
查看次数

"参考"解决了什么问题

在Chris的博客上:http://delphihaven.wordpress.com/2011/07/14/weird-in-more-ways-than-one/

我找到了以下代码

type
  TLinkVisitor<T> = reference to procedure(const Item: T);

  TDoubleLinked<T> = record
    Prev: ^TDoubleLinked<T>;
    Next: ^TDoubleLinked<T>;
    Value: T;
    class function Create(const aValue: T): Pointer; static;
    function Add(const aValue: T): Pointer;
    procedure Delete;
    procedure DeleteAll;
    function First: Pointer;
    function Last: Pointer;
    procedure ForEach(const Proc: TLinkVisitor<T>);
  end;
Run Code Online (Sandbox Code Playgroud)

"引用"关键字解决了哪些问题无法通过正常的程序类型完成?

delphi generics anonymous-methods

6
推荐指数
1
解决办法
157
查看次数

在调试模式下无法访问匿名类型的属性(VS2013)

在此示例控制台应用中:

class Program
{
    static void Main()
    {
        DoAsyncFoo();
        Console.ReadKey();
    }

    private static async void DoAsyncFoo()
    {
        var task = CollectStatsAsync();
        dynamic foo = await task;
        Console.WriteLine(foo.NumberOfCores);
    }

    private static async Task<dynamic> CollectStatsAsync()
    {
        return CollectStats();
    }

    private static dynamic CollectStats()
    {
        return new { NumberOfCores = 3 };
    }
}
Run Code Online (Sandbox Code Playgroud)

当我把断点放到

Console.WriteLine(foo.NumberOfCores)

并在调试模式下评估foo.NumberOfCores,错误的输出是:

gatherStats.NumberOfCores'对象'不包含'NumberOfCores'的定义,并且没有扩展方法'NumberOfCores'接受类型'object'的第一个参数可以找到(你是否缺少using指令或汇编引用?)

因为gatherStats是"匿名对象",而不是"动态".但是,该函数返回动态,我将其指定为动态.

评估成功:

((dynamic)foo).NumberOfCores;
Run Code Online (Sandbox Code Playgroud)

顺便说一下,我已经意识到如果我同步编写函数,调试器可以直接返回结果.所以它应该是异步的.

注意:我也尝试从函数返回Expando Object而不是Anonymous Type,结果是一样的.

c# asynchronous dynamic anonymous-methods visual-studio-2013

6
推荐指数
1
解决办法
412
查看次数

匿名方法对TypeInfo的奇怪行为

对于需要泛型类型"family"的一段代码,我尝试使用它TypeInfo来检索所需的信息.

class function GetTypeKind<T>:TTypeKind;
Run Code Online (Sandbox Code Playgroud)

对于大多数类型,我可以解决这个问题.但匿名方法类型表现出意外.

我有一个匿名方法类型定义为:

TMethodProc = reference to procedure;
Run Code Online (Sandbox Code Playgroud)

我试着获取类型信息:

MyKind := GetTypeKind<TMethodProc>;

class function GetTypeKind<T>:TTypeKind;
var 
  TI: PTypeInfo;
begin
  TI := TypeInfo(T);

  ...
end;
Run Code Online (Sandbox Code Playgroud)

我知道匿名方法背后有一些编译魔术.但我得到以下结果:

TI.TypeData.IntfParent == IInterface
TI.TypeData.IntfFlags == [(out of bounds)6]
Run Code Online (Sandbox Code Playgroud)

标志有一个意外的值,TIntfFlag有三个值,所以6是意外的.GUID也不是指导.它有一个相同的8个字节的重复集,大多数是00.例如(0,225,48,180,0,0,0,0,0,225,48,180,0,0,0,0)

匿名方法是否被排除在TypeInfo某些调整之外或者是否有用.

另外,(奇怪的)6是一个无证的特征,还是可以是任何值?

delphi anonymous-methods typeinfo delphi-10.2-tokyo

6
推荐指数
1
解决办法
185
查看次数