1

我正在使用扩展 CSharp 中的 LeMP v2.8.1,并具有以下用于定义和初始化类中的字段的快捷方式:

compileTimeAndRuntime 
{
    public partial class DI : IResolver
    {
        replace (T => ConcurrentDictionary<Type, Expression<Func<IResolver, object>>>) { public T Registrations = new T(); }
        replace (T => ConcurrentDictionary<Type, Func<IResolver, object>>) { public T DelegateCache = new T(); }
    }
}

public除了和internal修饰符之外,替换模式非常相似。但是让我们暂时跳过它们。

我的问题是有没有办法将此replace模式分解为一个define宏,这样我就不需要重复该模式。

我尝试了类似define New($T, $F) { $T $F = new $T(); }的方法,但是在将它与这样的 Type 参数一起使用时会吐出错误New(ConcurrentDictionary<Type, Expression<Func<IResolver, object>>>, Registrations)

4

1 回答 1

1

这个对我有用:

compileTimeAndRuntime 
{
    define New($T, $F) { $T $F = new $T(); }
    
    public partial class DI : IResolver
    {
        public New(ConcurrentDictionary<Type, Expression<Func<IResolver, object>>>, Registrations);
        internal New(ConcurrentDictionary<Type, Func<IResolver, object>>, DelegateCache);
    }
}

// Generated from Untitled.ecs by LeMP 2.8.2.0.
public partial class DI : IResolver
{
    public ConcurrentDictionary<Type, Expression<Func<IResolver, object>>> Registrations = new ConcurrentDictionary<Type, Expression<Func<IResolver, object>>>();
    internal ConcurrentDictionary<Type, Func<IResolver, object>> DelegateCache = new ConcurrentDictionary<Type, Func<IResolver, object>>();
}

这是一个更有趣的版本:

// Matches variable declarations and replaces __var with the type name.
// Useful to avoid repeating the type twice when declaring fields in classes.
[Passive] // avoids warning on variable declarations that don't match
define #var(__var, $name = new $T($(..args)) { $(..initializers) }) {
    $T $name = new $T($args) { $initializers };
}

public partial class DI : IResolver
{
    public __var Registrations = new ConcurrentDictionary<Type, Expression<Func<IResolver, object>>>();
    internal __var DelegateCache = new ConcurrentDictionary<Type, Func<IResolver, object>>();
    private __var _array = new int[4] { 0, 10, 20, 30 };
}

// Generated from Untitled.ecs by LeMP 2.8.2.0.
public partial class DI : IResolver
{
    public ConcurrentDictionary<Type, Expression<Func<IResolver, object>>> Registrations = new ConcurrentDictionary<Type, Expression<Func<IResolver, object>>>();
    internal ConcurrentDictionary<Type, Func<IResolver, object>> DelegateCache = new ConcurrentDictionary<Type, Func<IResolver, object>>();
    private int[] _array = new int[4] { 
        0, 10, 20, 30
    };
}

这是基于我的知识,它T x = y有一个 Loyc 树的形式#var(T, x = y),但是replace宏允许你在没有这些知识的情况下做同样的事情:

replace (
    { __var $name = new $Type($(..args)) { $(..initializers) }; } =>
    { $Type $name = new $Type($(..args)) { $(..initializers) }; });

很抱歉花了这么长时间来回答。

于 2020-07-29T05:58:46.087 回答