Question

I want to have a class like this (pseudocode):

public MyClass
{
   private bool isValid;

   [CheckValid]
   public int DoSomething()
   {
      return 1;
   }
}

Now, I want my [CheckValid] attribute to check isValid property, and if it is true, then allow DoSomething() to execute, or, if it is false, make DoSomething() return default(int) (or at least make the code inside DoSomething() inaccesible)

Était-ce utile?

La solution

That is not a feature of C#: attributes are not executed as such. There are, however, extension frameworks like PostSharp that would allow this - basically it rewrites the code at the IL level to inject functionality, typically based on attributes. But that requires additional tooling.

In C# "out of the box", your best bet would be:

public int DoSomething() {
    CheckValid(); // might throw an exception
    return 1;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top