C#中方法的CodeAttributeDeclaration [英] CodeAttributeDeclaration for methods in C#

查看:141
本文介绍了C#中方法的CodeAttributeDeclaration的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello Folks,

我是使用CodeDom的新手,并且在完成一些教程之后,我能够构建有趣的东西.但是,我在如何为方法设置自定义属性声明方面面临局限性.例如

[PexMethod(最大分支数= 1000)]
公共无效myMethod()
....

我只能声明[PexMethod()],但无法设置最大分支数..".我的意图是建立参数化的单元测试,然后让Pex探索我的自定义PUT方法.
如果有人可以给我一个提示,我将非常感谢.

提前谢谢.

Pedro

Hello Folks,

I am new using codeDom and after some tutorials I was able to build interesting things. However I am facing a limitation regarding how to set custom attributes declaration for a method. e.g.

[PexMethod (Max Branches = 1000)]
public void myMethod()
....

I am able to declare just [PexMethod()], but I am not able to set the "Max Branches..". My intention is to build parameterized unit tests and then let Pex explore my custom PUT method.
If someone could please give a hint I will really appreciate it.

Thanks in advance.

Pedro

推荐答案

属性功能强大,有用,但在几个方面都非常有限.但是-很高兴! -并不像您想的那样受到限制.它们仍然允许使用一些好的参数类型:
http://msdn.microsoft.com/en-us/library/ms177221%28v = vs.100%29.aspx [ ^ ].

这是您情况下的外观:
Attributes are powerful, useful, but very limited in several aspects. But — rejoice! — not that limited as you might think. They still allow some good set of parameter types:
http://msdn.microsoft.com/en-us/library/ms177221%28v=vs.100%29.aspx[^].

This is how it may look in your case:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
class PexMethodAttribute : System.Attribute {
    public int MaxBranches { internal get; set; }
}



注意internal.您只能在声明了该属性的同一程序集中检查该属性的值,这非常合理.很可能,您需要将setter set公开,因为您在应用该属性的代码中对其进行了设置.

这是将属性类型应用于某些方法的方法:



Pay attention for internal. You can check the attribute valued only in the same assembly where it is declared, which is pretty reasonable. Most likely, you will need to have the setter set public, because you set it in the code applying the attribute.

Here is how you can apply your attribute type to some method:

[PexMethod(MaxBranches = 1000)]
void SomeMethod(/* ... */) {/* ... */}



另外,您可以对参数使用构造函数语法:



Alternatively, you can use constructor syntax for the parameter:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
class PexMethodAttribute : System.Attribute {
    internal int MaxBranches { get; set; }
    public PexMethodAttribute(int maxBranches) { this.MaxBranches = maxBranches; }
}



而且它的应用看起来会有所不同:



And the application of it would look a bit different:

[PexMethod(1010)]
void SomeMethod(/* ... */) {/* ... */}



—SA



—SA


这篇关于C#中方法的CodeAttributeDeclaration的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆