vendredi 20 janvier 2017

Suppressing Code Analysis warning if custom attribute is present

I've made a custom attribute that when attached to a method, will cause that method to be called by reflection. However, I'm getting code analysis warnings that indicate the method has no upstream callers (it's private, because I don't want anything else calling it).

Obviously I can suppress that easily enough, but it does clutter the code file. Is there any way to have this warning automatically suppressed for any methods that have this attribute?

For example:

public class ArbitraryClass
{
    [RunOnStartUp]
    private static void RunThisOnStartup()
    {
        // Do some important stuff that can only be done on startup.
    }
}

public static class Program
{
    public static void Main()
    {
        AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(assembly => assembly.GetTypes())
            .SelectMany(type => type.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic))
            .Where(method => method.GetCustomAttribute<RunOnStartupAttribute>() != null)
            .ToList()
            .ForEach(method => method.Invoke(null, new object[0]));

        // Start up the main form etc.
    }
}

(Yes, I know I could probably just use a static initializer in this case, but 'on startup' isn't the only circumstance I use this for).





Aucun commentaire:

Enregistrer un commentaire