简体   繁体   中英

c# ambiguous attributes

i read the following great question: Attributes in C# and learned a lot about attributes.

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. 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 Mine = MyOwnSuperNamespace;
using Theirs = 3rdPartyNamespace;

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

You can extend State attribute and add your own properties. 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? That's quite impossible. You'll need to specify both, and use the namespace as well to avoid the ambiguity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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