如何在我的属性设置动态值 [英] How to set dynamic value in my Attribute
问题描述
我想传递一个动态的变量作为参数传递给我的属性。在这里,我想用Environment.MachineName,请参见下面的code:
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 IMonitoringViewModelConfiguration : IConfigurationContainer
{
[ConfigurationKey("MonitoringService", Environment.MachineName)]
string ConnectionString { get; }
}
但是我得到这个错误:
错误1的属性参数必须是一个常量前pression,属性参数类型的typeof前pression或数组创建前pression Abc.ServiceBus.Monitoring.ViewModel
But I get this error: Error 1 An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Abc.ServiceBus.Monitoring.ViewModel
有任何解决方法尽可能的干净,以通过我的Environment.MachineName?
Is there any workaround as clean as possible in order to pass my Environment.MachineName ?
感谢。
约翰
PS:我发现一些物件,说说这个情况,但它已被写入像两三年前。但今天,确实这是从.NET 4.0的CLR提供了一些很好的解决方案?
PS: I've found some articles which talk about this case but it have been written like 2-3 years ago. But today, does the clr which comes from .NET 4.0 gives some nice solution ?
推荐答案
您可以创建一个特殊值枚举,并在属性单独构造函数重载接受他们:
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)]
这篇关于如何在我的属性设置动态值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!