C# Attributes mandatory property

前端 未结 3 1176
时光说笑
时光说笑 2021-01-14 03:00

I\'ve created attribute like

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    [Serializable]
    public class TestPropertyAttribute :          


        
3条回答
  •  臣服心动
    2021-01-14 03:13

    Put it in the constructor instead of just as a separate property:

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    [Serializable]
    public class TestPropertyAttribute : System.Attribute
    {
        readonly string _name;
    
        public TestPropertyAttribute(string name)
        {
            _name = name;
        }
    
        public string Name { get { return _name; } }
    }
    

    I don't believe you can make it mandatory and use the Name=... syntax when applying the attribute though.

提交回复
热议问题