简体   繁体   English

C#模棱两可的属性

[英]c# ambiguous attributes

i read the following great question: Attributes in C# and learned a lot about attributes. 我阅读了以下重要问题: C#中的属性,并学到了很多有关属性的知识。

i am using a library that uses several attributes. 我正在使用使用多个属性的库。 example: 例:

[State]
public class USStates
{
    [City]
    public void isNewYork() { }
    [Zip]
    public ZipCode GetZipCode() { }
}

i wanted to create my own attributes and perform additional work on my classes using existing attributes (State, City, Zip) which are from a 3rd party namespace. 我想创建自己的属性,并使用来自第三方名称空间的现有属性(州,城市,邮编)对我的类进行其他工作。 for example, i'm trying to achieve this: 例如,我正在努力实现这一目标:

using 3rdPartyNamespace;
using MyOwnSuperNamespace;

public class State : Attribute 
{ 
    // my own implementation/extension of State 
}

// create City, Zip attributes respectively

[State]
public class USStates
{
    [City]
    public void isNewYork() { }
    [Zip]
    public ZipCode GetZipCode() { }
}

i tried the above but keeping getting an ambiguous attribute error on all 3 attributes. 我尝试了上述方法,但在所有3个属性上均得到了模棱两可的属性错误。 ho can i tell the compiler to direct call to both attributes instead of using either one? 我如何告诉编译器直接调用这两个属性而不是使用其中一个? i would like to keep the existing attributes and perform additional work without having to mark my classes with additional attributes that i have created. 我想保留现有属性并执行其他工作,而不必用我创建的其他属性来标记我的班级。

is this possible? 这可能吗?

ho can i tell the compiler to direct call to both attributes instead of using either one? 我如何告诉编译器直接调用这两个属性而不是使用其中一个?

If you want to apply both attributes, you need to specify both attributes. 如果要应用两个属性,则需要指定两个属性。 You'll need to either fully-qualify the attribute names, or use using alias directives, eg 您需要完全限定属性名称,或使用别名指令using ,例如

using Mine = MyOwnSuperNamespace;
using Theirs = 3rdPartyNamespace;

[Mine.State]
[Theirs.State]
...

You can extend State attribute and add your own properties. 您可以扩展State属性并添加自己的属性。 For example: 例如:

public class MyState : StateAttribute
{ 
    public string MyProperty {get;set;}
}

// create City, Zip attributes respectively

[MyState {MyProperty = "Test"}]
public class USStates
{
    [City]
    public void isNewYork() { }
    [Zip]
    public ZipCode GetZipCode() { }
}

you can check attribute this way: 您可以通过以下方式检查属性:

USStates states = new USStates();
var attribute = states.GetType().GetCustomAttributes(typeof(MyStateAttribute, false)).FirstOrDefault();
if (attribute != null)
{
  var prop = attribute.MyProperty;
 // Do stuff..
}

You want [State] to resolve to both attributes? 您要[State]解析为两个属性? That's quite impossible. 那是完全不可能的。 You'll need to specify both, and use the namespace as well to avoid the ambiguity. 您需要同时指定两者,并同时使用命名空间,以避免产生歧义。

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

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