【问题标题】:Iterating over a type's members at compile time在编译时迭代类型的成员
【发布时间】:2011-09-23 21:23:00
【问题描述】:

是否有任何静态类型的强类型编译语言提供在编译时迭代类型成员并为每个成员生成模板化代码的功能?例如,它可能是这样的:

// in pseudo-C#

public static void AddParameter(string parameterName, object value) { /* ... */ }

public static void AddParameters<T>(T parameters) {
    // Of course, the memberof(T), membersof(T), membername(<member>)
    // and membervalue(<member>, object) operators would be valid
    // inside a "compile for" block only
    compile for (memberof(T) member in membersof(T))
        AddParameter(membername(member), membervalue(member, parameters));

    /* If this were actual C#, the "compile for" block could even have a where clause */
}

所以,如果进行了以下调用:

StaticClass.AddParameters(new { UserID = "eleon", Password = "Gu3$$17" });

然后AddParameters 的特定实例化将展开到

public static void AddParameters(InternalNameOfTheAnonymousType parameters) {
    AddParameters("UserID",   parameters.UserID);
    AddParameters("Password", parameters.Password);
}

在编译时(如果它是在 IL-to-native 编译时的实际 C#)

【问题讨论】:

  • @Marcin:我不会将我必须编写的代码量减少约 15%(这​​是一个保守的估计)称为“过早的优化”。
  • @Marcin:我目前在泛型方法AddParameters 中使用反射,但是,由于反射很慢,我必须保持愚蠢的静态Dictionary&lt;Type, PropertyInfo[]&gt;s 以避免多次调用Type.GetProperties()同一类型。
  • 哈希表是如何低效的?
  • @Eduardo Leon:所以使用不同类型的字典结构,比如 alist。

标签: programming-languages


【解决方案1】:

您可以使用Nemerle 来完成。

【讨论】:

  • 非常好!除了 .NET 运行时,Nemerle 是否需要特定的运行时?如果没有,我现在就开始使用它。
  • @Eduardo León,它不添加任何依赖项。您还可以使用几乎完整的 C# 作为源语言,仅在需要时使用 Nemerle 特定的功能。
【解决方案2】:

这里的句法荆棘很厚,所以我很难看出你在说什么,但我认为 Haskell 的 Scrap Your Boilerplate 可能足够强大,可以做到这一点。它当然能够进行一些惊人的编译时通用元编程。

【讨论】:

    猜你喜欢
    • 2022-07-11
    • 2016-04-08
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    相关资源
    最近更新 更多