Let's say I have the following attributes:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
class TestAttribute : Attribute { }
class FooAttribute : TestAttribute { }
class BarAttribute : TestAttribute { }
I expect the attributes inherited from TestAttribute
can't be duplicated for methods:
[Foo][Bar] //I expect compile error here
void M() { }
But in fact the AllowMultiple
check is only applied in the same attribute type, means compile errors happen for [Test][Test]
,[Foo][Foo]
,[Bar][Bar]
, but no error for [Test][Foo]
,[Foo][Bar]
.
It looks like by design than a bug? But with the definition of TestAttribute
someone can easily make mistake like this:
//bang! why? AllowMultiple=false!
var testAttribute = someMethod.GetCustomAttribute<TestAttribute>();
//or someMethod.GetCustomAttributes<TestAttribute>().SingleOrDefault();
My questions are:
Q1: Why do they design it like this? I think my expected behavior is more "correct"?
Q2: Any workaround? I don't want to put Foo/Bar things to an enum and use something like [Test(Flag=Foo)]
, because the inherited attributes have their different properties, putting them into one attribute is hard to maintain.
Aucun commentaire:
Enregistrer un commentaire