简体   繁体   English

属性:避免代码重复

[英]Attribute: avoid code duplication

[MyAttribute(Name = "Test123"]
public MyClass
{
    public string Name 
    {
       get { return "Test123"; }
    }
}

Is this code sample, I need to define the name two times. 是此代码示例,我需要定义两次名称。 One time in the attribute and one time in the class itself. 在属性中一次,在类本身中一次。 Is there a way to avoid this kind of duplication? 有办法避免这种重复吗?

I need both because sometime, I'm iterating through the assembly to find all class that use MyAttribute and to list them (with the name). 我需要两者,因为有时我要遍历程序集以查找所有使用MyAttribute的类并列出它们(并带有名称)。 Other time, I've access to the instantiated object so I don't want to use the attribute. 其他时间,我可以访问实例化的对象,所以我不想使用该属性。

If the name can be put into a string constant, then you can use that constant for both the attribute parameter and also the return value of the property. 如果可以将名称放入字符串常量中,则可以将该常量同时用于attribute参数和属性的返回值。

If you ever need to change the name, just change the const value. 如果您需要更改名称,只需更改const值即可。

[MyAttribute(MyClass.MyClassName)]
public MyClass
{
    private const string MyClassName = "Test123";

    public string Name 
    {
       get { return MyClass.MyClassName; }
    }
}

Something like the following might work. 类似以下内容可能会起作用。 It will be god-awfully inefficient though. 但这真是低效的。 Note, I have not tested the below code but it should be close. 注意,我还没有测试下面的代码,但是应该将其关闭。

[MyAttribute(Name = "Test123"]
public MyClass
{
    public string Name 
    {
       get { return ((MyAttribute)(GetType().GetCustomAttributes(typeof(MyAttribute), true).First())).Name; }
    }
}

Why do you need an attribute and a property in the first place though? 为什么首先需要一个属性和一个属性? The fact that you need both, especially since the Name attribute is "static" (attached to the type) and the property is instance, smells wrong. 两者都需要的事实,特别是因为Name属性是“静态”(附加到类型上)并且属性是instance,这听起来很错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM