C#: Making sure parameter has attribute
I have an attribute lets call it SomeAttribute and a class i need to make sure the class is passed a type which has SomeAttribute. So this is how 开发者_Python百科i do it now:
public class Test()
{
public Test(SomeType obj)
{
if(!obj.GetType().IsDefined(typeof(SomeAttribute), false))
{
throw new ArgumentException("Errormessage");
}
}
}
But this means that i don't get any errors at compile time but somewhere at runtime, if obj does not have the attribute. Is there a way to specify in the method declaration that the parameter must have some attribute ? So i get errors i compile time when using the wrong parameters, or do i have to use an empty interface ?
There's no way to enforce an attribute at compile-time. You may want to reconsider your design - usually attributes are more about metadata, less about runtime behavior.
NDepend's Code Query Language is a static anlysis tool that could probably detect violations - but if you're not already using NDepend, I'd be hesitant to include it for this requirement alone.
Then again, lacking context of what you want to do - it's a bit like solving the other half your problem.
No, there's no way of requiring an attribute - but you could always write unit tests to scan through your assemblies and check that the appropriate attributes had been applied - assuming you can actually detect this requirement.
It sounds somewhat odd though - could you give some more details as to why you're using this scheme? Perhaps another approach would be more appropriate, such as another parameter to describe the extra data you're interested in.
精彩评论