How to set dynamic value in my Attribute

后端 未结 2 1843
余生分开走
余生分开走 2020-11-28 15:25

I would like to pass a dynamic variable as a parameter to my attribute. Here I want to use Environment.MachineName, see the code below:

public interface IMon         


        
相关标签:
2条回答
  • 2020-11-28 15:43

    Attribute parameters are evaluated at compile time, not at runtime. So they have to be compile time constants...

    However, you could create a derived class LocalMachineConfigurationKey attribute that takes only one parameter and uses Environment.MachineName at runtime to evaluate the property.

    public class ConfigurationKeyAttribute : Attribute
    {
        private readonly string _key;
        private readonly string _machineName;
    
        public ConfigurationKeyAttribute(string key, string machineName)
        {
            _key = key;
            _machineName = machineName;
        }
    
        protected ConfigurationKeyAttribute(string key) : this(key, null)
        {
        }
    
        public string Key { get { return _key; } }
        public virtual string MachineName { get { return _machineName; } }
    }
    
    public class LocalMachineConfigurationKeyAttribute : ConfigurationKeyAttribute
    {
        public LocalMachineConfigurationKeyAttribute(string key) : base(key)
        {
        }
    
        public override string MachineName { get { return Environment.MachineName; } }
    }
    
    0 讨论(0)
  • 2020-11-28 16:00

    You could create an enum with special values, and accept them in a separate constructor overload in the attribute:

    enum SpecialConfigurationValues
    {
        MachineName
        // , other special ones
    }
    
    class ConfigurationKeyAttribute : Attribute
    {
        private string _key;
        private string _value;
    
        public ConfigurationKeyAttribute(string key, string value)
        {
            // ...
        }
    
        public ConfigurationKeyAttribute(string key, SpecialConfigurationValues specialValue)
        {
            _key = key;
            switch (specialValue)
            {
                case SpecialConfigurationValues.MachineName:
                    _value = Environment.MachineName;
                    break;
                // case <other special ones>
            }
        }
    }
    
    [ConfigurationKey("MonitoringService", SpecialConfigurationValues.MachineName)]
    
    0 讨论(0)
提交回复
热议问题