我知道属性非常有用。有一些预定义的属性,例如[Browsable(false)],它允许您在财产选项卡中隐藏财产。下面是一个解释属性的好问题:.NET中的属性是什么?
您在项目中实际使用的预定义属性(及其名称空间)是什么?
我知道属性非常有用。有一些预定义的属性,例如[Browsable(false)],它允许您在财产选项卡中隐藏财产。下面是一个解释属性的好问题:.NET中的属性是什么?
您在项目中实际使用的预定义属性(及其名称空间)是什么?
当前回答
当您在调试期间将鼠标悬停在Type的实例上时,[DuggerDisplay]对于快速查看该类型的自定义输出非常有用。例子:
[DebuggerDisplay("FirstName={FirstName}, LastName={LastName}")]
class Customer
{
public string FirstName;
public string LastName;
}
这是它在调试器中的外观:
此外,值得一提的是,设置了CacheDuration属性的[WebMethod]属性可以避免不必要地执行web服务方法。
其他回答
如果项目不在您的解决方案中,[EditorBrowsable(EditorBrowsableState.Never)]允许您对IntelliSense隐藏财产和方法。非常有助于隐藏流畅接口的无效流。您希望多长时间使用GetHashCode()或Equals()?
对于MVC,[ActionName(“Name”)]允许您使用相同的方法签名进行Get操作和Post操作,或者在操作名称中使用破折号,否则,如果不为其创建路由,就无法实现这一点。
当您在调试期间将鼠标悬停在Type的实例上时,[DuggerDisplay]对于快速查看该类型的自定义输出非常有用。例子:
[DebuggerDisplay("FirstName={FirstName}, LastName={LastName}")]
class Customer
{
public string FirstName;
public string LastName;
}
这是它在调试器中的外观:
此外,值得一提的是,设置了CacheDuration属性的[WebMethod]属性可以避免不必要地执行web服务方法。
我喜欢将[ThreadStatic]属性与基于线程和堆栈的编程结合使用。例如,如果我希望一个值与调用序列的其余部分共享,但我希望在带外(即调用参数之外)执行,我可以使用类似的方法。
class MyContextInformation : IDisposable {
[ThreadStatic] private static MyContextInformation current;
public static MyContextInformation Current {
get { return current; }
}
private MyContextInformation previous;
public MyContextInformation(Object myData) {
this.myData = myData;
previous = current;
current = this;
}
public void Dispose() {
current = previous;
}
}
稍后在我的代码中,我可以使用它向代码下游的人提供带外的上下文信息。例子:
using(new MyContextInformation(someInfoInContext)) {
...
}
ThreadStatic属性允许我将调用范围仅限于所讨论的线程,避免了跨线程访问数据的混乱问题。
我认为这里必须提到以下属性也非常重要:
STAThreadAttribute
指示应用程序的COM线程模型是单线程单元(STA)。
例如,此属性用于Windows窗体应用程序:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
而且。。。
SuppressMessageAttribute
禁止报告特定的静态分析工具规则冲突,允许对单个代码工件进行多次禁止。
例如:
[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "isChecked")]
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "fileIdentifier")]
static void FileNode(string name, bool isChecked)
{
string fileIdentifier = name;
string fileName = name;
string version = String.Empty;
}
我总是将DisplayName、Description和DefaultValue属性用于我的用户控件、自定义控件或我将通过属性网格编辑的任何类的公共财产。.NET PropertyGrid使用这些标记来设置未设置为默认值的名称、描述面板和粗体值的格式。
[DisplayName("Error color")]
[Description("The color used on nodes containing errors.")]
[DefaultValue(Color.Red)]
public Color ErrorColor
{
...
}
如果找不到XML注释,我只希望Visual Studio的IntelliSense将Description属性考虑在内。这样可以避免同一句话重复两次。