如何在我的属性中设置动态值 [英] How to set dynamic value in my Attribute

查看:20
本文介绍了如何在我的属性中设置动态值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将动态变量作为参数传递给我的属性.这里我想使用Environment.MachineName,看下面的代码:

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 ​​属性参数必须是属性参数类型 Abc.ServiceBus.Monitoring.ViewModel 的常量表达式、typeof 表达式或数组创建表达式

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:我找到了一些谈论这个案例的文章,但它是在 2-3 年前写的.但是今天,来自 .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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆