【问题标题】:What .Net attributes do people apply to their code? [duplicate]人们将哪些 .Net 属性应用于他们的代码? [复制]
【发布时间】:2010-01-16 11:07:08
【问题描述】:

可能重复:
Most Useful Attributes in C#

我总是觉得我缺少可以通过简单地将属性应用于类、方法、属性等来在 .Net 中获得的功能。智能感知无法显示所有适当的属性也无济于事,因为它们通常可以应用于广泛的场景。

以下是我喜欢使用的几个属性:

[DebuggerHidden] - 将其置于方法之上可防止 Visual Studio 调试器单步执行代码。如果您有一个事件不断触发并中断您的调试,这将非常有用。

[EditorBrowsable(EditorBrowsableState.Never)] - 对智能感知隐藏方法。我不经常使用它,但是在构建可重用组件并且您想隐藏一些测试或调试方法时它很方便。

我想看看其他人在使用什么以及人们有什么建议。

【问题讨论】:

  • +1 好问题,希望看到一些回复。
  • 我实际上将投票结束,因为这不是一个真正的问题。答案是“全部”。这些属性不是为了不被使用而创建的。
  • 对不起,我在问之前搜索过。我不是在寻找必须使用属性的答案。像 ComVisible 一样使用 Com。我一直在寻找真正通用的那些正在使用的。

标签: .net attributes


【解决方案1】:

我刚刚找到了这个资源:

 

// The DebuggerDisplayAttribute can be a sweet shortcut to avoid expanding
// the object to get to the value of a given property when debugging. 
[DebuggerDisplay("ProductName = {ProductName},ProductSKU= {ProductSKU}")] 
public class Product 
{ 
    public string ProductName { get; set; } 
    public string ProductSKU { get; set; } 
}

// This attribute is great to skip through methods or properties 
// that only have getters and setters defined.
[DebuggerStepThrough()] 
public virtual int AddressId 
{ 
    get { return _AddressId;}     
    set 
    { 
        _AddressId = value;   
        OnPropertyChanged("AddressId"); 
    } 
}

// The method below is marked with the ObsoleteAttribute. 
// Any code that attempts to call this method will get a warning.
[Obsolete("Do not call this method.")]
private static void SomeDeprecatedMethod() { }

// similar to using a combination of the DebuggerHidden attribute, which hides
// the code from the debugger, and the DebuggerStepThrough attribute, which tells
// the debugger to step through, rather than into, the code it is applied to.
[DebuggerNonUserCode()]
private static void SomeInternalCode() { }

【讨论】:

    【解决方案2】:

    我们有很多符合 CLS 的代码,有些不符合,所以这对我们来说显然是一个加分项:

    [assembly:CLSCompliant(true)]
    [CLSCompliant(true)]
    

    这对我们帮助很大。

    【讨论】:

    • 哦,[ComVisibleAttribute(true)]
    【解决方案3】:

    我通常使用 [Browsable(false)][Serializable]

    [Browsable(false)] 属性对 PropertyGrid 隐藏属性。

    这不应该是社区维基吗?

    【讨论】:

    • 我是这个网站的新手,我还没有看过维基,现在我会看的。谢谢
    【解决方案4】:

    我真的很喜欢DebuggerDisplay

    [DebuggerDisplay("Count = {count}")]
    class MyHashtable
    {
        public int count = 4;
    }
    

    它会指示 VS 在将鼠标悬停在项目上时显示什么。

    【讨论】:

      【解决方案5】:
      [DebuggerDisplay(....)]
      

      定义我想在调试器显示中看到的结构或类的哪些字段。

      【讨论】:

        【解决方案6】:

        有时 BindableAttribute 可以很好地影响组件的绑定行为。 启动反射器并搜索“属性”并浏览一下可能会有所帮助。这取决于您的意图,哪些有用。

        【讨论】:

          【解决方案7】:

          我使用了条件属性 在创建演示应用程序期间。我将其制作为完整版本,并使用这些类型的属性抑制了一些功能。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-09-14
            • 1970-01-01
            • 2014-07-13
            • 1970-01-01
            • 1970-01-01
            • 2013-03-30
            • 1970-01-01
            • 2015-04-20
            相关资源
            最近更新 更多