区分封闭类

时间:2015-10-14 14:13:57

标签: c# lambda mono closures portability

我需要一种可靠的方法来区分编译器生成的闭包对象。

我使用CompilerGeneratedAttribute找到了一个可行的解决方案:How to distingush compiler-generated classes from user classes in .NET 事实证明我可以使用CompilerGeneratedAttribute。

这是我目前的代码:

static bool IsClosure(Type t)
{
    return IsCompilerGenerated(t) && !t.Name.Contains("AnonymousType");
}

static bool IsCompilerGenerated(Type t)
{
    return Attribute.IsDefined(t, typeof(CompilerGeneratedAttribute), false);
}

void Main()
{
    var site = new Model();

    var propertyExpression = (Expression<Func<string>>)(() => site.Prop);
    var memberAccess = (MemberExpression)propertyExpression.Body;
    var modelExpression = (MemberExpression)memberAccess.Expression;
    var closureExpression = (ConstantExpression)modelExpression.Expression;
    var closureType = closureExpression.Value.GetType();

    Console.WriteLine("Type: {0} Is closure: {1}", closureType, IsClosure(closureType));

    var anonymous = new { x = 0 };

    Console.WriteLine("Type: {0} Is closure: {1}", anonymous.GetType(), IsClosure(anonymous.GetType()));
}

class Model
{
    public string Prop { get; set; }
}

输出:

Type: MyClass+<>c__DisplayClass0_0 Is closure: True
Type: <>f__AnonymousType0`1[System.Int32] Is closure: False

据我和Anonymous Types - Are there any distingushing characteristics?了解匿名对象,编译器生成的闭包类型的问题是类似的,区别特征本质上是一个实现细节。是这样的吗?

是否有更可靠的方法来区分闭包对象,考虑到.NET的单声道版本和未来版本的可移植性?

0 个答案:

没有答案