我知道属性非常有用。有一些预定义的属性,例如[Browsable(false)],它允许您在财产选项卡中隐藏财产。下面是一个解释属性的好问题:.NET中的属性是什么?

您在项目中实际使用的预定义属性(及其名称空间)是什么?


当前回答

在我的脑海中,这里是一个快速列表,大致按使用频率排序,列出了我在一个大型项目中实际使用的预定义属性(约50万个LoC):

标志,可串行化,WebMethod,COMVisible,TypeConverter,Conditional,ThreadStatic,Obsolete,InternalsVisibleTo,DebuggerStepThrough。

其他回答

DebuggerHiddenAttribute,它允许避免单步执行不应调试的代码。

public static class CustomDebug
{
    [DebuggerHidden]
    public static void Assert(Boolean condition, Func<Exception> exceptionCreator) { ... }
}

...

// The following assert fails, and because of the attribute the exception is shown at this line
// Isn't affecting the stack trace
CustomDebug.Assert(false, () => new Exception()); 

此外,它还防止在堆栈跟踪中显示方法,这在使用只包装另一个方法的方法时非常有用:

[DebuggerHidden]
public Element GetElementAt(Vector2 position)
{
    return GetElementAt(position.X, position.Y);
}

public Element GetElementAt(Single x, Single y) { ... }

如果现在调用GetElementAt(新的Vector2(10,10)),并且包装的方法发生错误,那么调用堆栈不会显示正在调用引发错误的方法的方法。

[DeploymentItem(“myFile1.txt”)]DeploymentItem上的MSDN文档

如果您正在对文件进行测试或将该文件用作测试的输入,那么这非常有用。

我通过CodeSmith生成数据实体类,并为一些验证例程使用属性。下面是一个示例:

/// <summary>
/// Firm ID
/// </summary>
[ChineseDescription("送样单位编号")]
[ValidRequired()]
public string FirmGUID
{
    get { return _firmGUID; }
    set { _firmGUID = value; }
}

我得到了一个实用程序类,根据附加到数据实体类的属性进行验证。代码如下:

namespace Reform.Water.Business.Common
{
/// <summary>
/// Validation Utility
/// </summary>
public static class ValidationUtility
{
    /// <summary>
    /// Data entity validation
    /// </summary>
    /// <param name="data">Data entity object</param>
    /// <returns>return true if the object is valid, otherwise return false</returns>
    public static bool Validate(object data)
    {
        bool result = true;
        PropertyInfo[] properties = data.GetType().GetProperties();
        foreach (PropertyInfo p in properties)
        {
            //Length validatioin
            Attribute attribute = Attribute.GetCustomAttribute(p,typeof(ValidLengthAttribute), false);
            if (attribute != null)
            {
                ValidLengthAttribute validLengthAttribute = attribute as ValidLengthAttribute;
                if (validLengthAttribute != null)
                {
                    int maxLength = validLengthAttribute.MaxLength;
                    int minLength = validLengthAttribute.MinLength;
                    string stringValue = p.GetValue(data, null).ToString();
                    if (stringValue.Length < minLength || stringValue.Length > maxLength)
                    {
                        return false;
                    }
                }
            }
            //Range validation
            attribute = Attribute.GetCustomAttribute(p,typeof(ValidRangeAttribute), false);
            if (attribute != null)
            {
                ValidRangeAttribute validRangeAttribute = attribute as ValidRangeAttribute;
                if (validRangeAttribute != null)
                {
                    decimal maxValue = decimal.MaxValue;
                    decimal minValue = decimal.MinValue;
                    decimal.TryParse(validRangeAttribute.MaxValueString, out maxValue);
                    decimal.TryParse(validRangeAttribute.MinValueString, out minValue);
                    decimal decimalValue = 0;
                    decimal.TryParse(p.GetValue(data, null).ToString(), out decimalValue);
                    if (decimalValue < minValue || decimalValue > maxValue)
                    {
                        return false;
                    }
                }
            }
            //Regex validation
            attribute = Attribute.GetCustomAttribute(p,typeof(ValidRegExAttribute), false);
            if (attribute != null)
            {
                ValidRegExAttribute validRegExAttribute = attribute as ValidRegExAttribute;
                if (validRegExAttribute != null)
                {
                    string objectStringValue = p.GetValue(data, null).ToString();
                    string regExString = validRegExAttribute.RegExString;
                    Regex regEx = new Regex(regExString);
                    if (regEx.Match(objectStringValue) == null)
                    {
                        return false;
                    }
                }
            }
            //Required field validation
            attribute = Attribute.GetCustomAttribute(p,typeof(ValidRequiredAttribute), false);
            if (attribute != null)
            {
                ValidRequiredAttribute validRequiredAttribute = attribute as ValidRequiredAttribute;
                if (validRequiredAttribute != null)
                {
                    object requiredPropertyValue = p.GetValue(data, null);
                    if (requiredPropertyValue == null || string.IsNullOrEmpty(requiredPropertyValue.ToString()))
                    {
                        return false;
                    }
                }
            }
        }
        return result;
    }
}
}

只有少数属性获得编译器支持,但AOP中有一个非常有趣的属性用法:PostSharp使用您定制的属性将IL注入到方法中,允许各种功能。。。log/trace是一些微不足道的示例,但其他一些好的示例是自动INotifyPropertyChanged实现(此处)。

一些发生并直接影响编译器或运行时:

[条件(“FOO”)]-只有在生成期间定义了“FOO“符号时,才会调用此方法(包括参数求值)[MethodImpl(…)]-用于指示一些事情,如同步、内联〔PrincipalPermission(…)〕-用于将安全检查自动注入代码[TypeForwardedTo(…)]-用于在程序集之间移动类型,而不重新生成调用方

对于通过反射手动检查的东西,我非常喜欢System.ComponentModel属性;像[TypeDescriptionProvider(…)]、[TypeConverter(…)】和[Editor(…)]]这样的东西可以完全改变数据绑定场景中类型的行为(即动态财产等)。

我使用最多的属性是与XML序列化相关的属性。

XmlRoot

Xml元素

XmlAttribute

在进行任何快速而肮脏的XML解析或序列化时非常有用。