gpt4 book ai didi

c# - 在 C# 中生成类似于使用装饰器的代码的最佳方法?

转载 作者:可可西里 更新时间:2023-11-01 03:09:04 24 4
gpt4 key购买 nike

假设我有一个不断重复的模式。像这样的东西:

static class C {
[DllImport("mydll")]
private static extern uint MyNativeCall1(Action a);
public static uint MyWrapper1(Action a) {
// Do something
return MyNativeCall1(a);
}

[DllImport("mydll")]
private static extern uint MyNativeCall2(Action a);
public static uint MyWrapper2(Action a) {
// Do something
return MyNativeCall2(a);
}

//...

[DllImport("mydll")]
private static extern uint MyNativeCallN(Action a);
public static uint MyWrapperN(Action a) {
// Do something
return MyNativeCallN(a);
}
}

所有这些中唯一不同的是 native 函数和包装器方法的名称。有没有办法通过装饰器之类的东西生成它们?起初我以为 C# 属性是装饰器。也就是说,我可以通过 [GenerateScaffolding("MyNativeCall1")] 之类的方式生成代码。但似乎属性更像是注解,实例化一个包含一些元数据的类。

C# 也没有宏。那么有什么办法可以做到这一点吗?

需要注意的几点:

  • 想法是包装器方法有额外的代码;他们不仅仅是调用 native 函数。
  • 这个想法还在于,生成的代码可以与类中的其他现有代码交错,而不是生成类文件本身;类似于装饰器或 C/C++ 宏。
  • 该方法不应依赖于任何特定的 IDE。具体来说,我不使用 Visual Studio。

最佳答案

从这个 MSDN article 中汲取灵感在 T4 模板上,您可以这样:

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
static class C {
<#
int N = 15;
for(int i=0; i<N; i++)
{ #>
[DllImport("mydll")]
private static extern uint MyNativeCall<#= i #>(Action a);
public static uint MyWrapper<%#= i #>(Action a) {
return MyNativeCall<#= i #>(a);
}
<# } #>
}

关于c# - 在 C# 中生成类似于使用装饰器的代码的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24402625/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com